Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/google-app-engine/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Django中创建请求对象?_Django_Google App Engine_Request_Httprequest - Fatal编程技术网

如何在Django中创建请求对象?

如何在Django中创建请求对象?,django,google-app-engine,request,httprequest,Django,Google App Engine,Request,Httprequest,所以我将Django与Google App Engine一起使用,我有一个url.py文件,它将每个url重定向到相应的方法。这些方法中的每一个都会作为参数之一自动传递“request”,我相信这是一个HttpRequest对象 如何从代码中创建这个填充的请求对象?例如,如果我在代码深处的某个方法中,我希望能够访问此请求对象,而不必将其传递给每个函数以确保其可用。假设urls.py调用方法foo,我目前的做法是: foo(request): # stuff here bar(re

所以我将Django与Google App Engine一起使用,我有一个url.py文件,它将每个url重定向到相应的方法。这些方法中的每一个都会作为参数之一自动传递“request”,我相信这是一个HttpRequest对象

如何从代码中创建这个填充的请求对象?例如,如果我在代码深处的某个方法中,我希望能够访问此请求对象,而不必将其传递给每个函数以确保其可用。假设urls.py调用方法foo,我目前的做法是:

foo(request):
    # stuff here
    bar(request)
     # more stuff here

bar(request):
     # stuff here<stuff>
    baz(request)
     # more stuff here

baz(request):
    do something with request here
i、 如果我不需要的话,就不要传递请求。但是,doing request=HttpRequest() 返回一个空的请求对象…我想要的是一个完全填充的版本,就像从url.py调用的每个方法中传递的一样

我在这里浏览了HttpRequest的文档: 但我没想到怎么做

任何想法都将不胜感激

谢谢,
Ryan

只需在视图定义之前创建一个请求变量,并在从视图接收时设置其值(使用示例代码):

见:


更新:与您的非常相似,公认的解决方案基本上是创建一个全局请求变量并将其附加到设置中。

request=HttpRequest()
将为您提供一个空变量,但您可以向其写入内容

以下是我在项目中使用的一个示例:

def new(request):
    ...
    newrequest = HttpRequest()
    newrequest.method = 'GET'
    newrequest.user = request.user
    resp = result_email(newrequest , obj-id , token )
    send_email( resp , ... )
    return HttpResponseRedirect( ... )
    ...
def result_email(request , ...):
    ...
    return render(request , ...)

抱歉,兰斯,我认为我没有很好地解释我最初发布的帖子中的问题。我已经更新了它…希望它现在更清晰。我仍然认为这个问题与变量范围有关。我已经更新了我的答案以使用全局变量。谢谢Lance。我的函数都在不同的.py文件中,我真的不想走使用全局变量的路线。看看我在上次编辑中链接到的另一个问题。如果你真的找到了更好的解决方案,请让我们知道。这不是最漂亮的方法,但感谢链接为我工作。谢谢
current_request = None

foo(request):
    current_request = request
    # stuff here
    bar()
    # more stuff here

bar():
     # stuff here
    baz()
     # more stuff here

baz():
    # do something with currest_request here
def new(request):
    ...
    newrequest = HttpRequest()
    newrequest.method = 'GET'
    newrequest.user = request.user
    resp = result_email(newrequest , obj-id , token )
    send_email( resp , ... )
    return HttpResponseRedirect( ... )
    ...
def result_email(request , ...):
    ...
    return render(request , ...)