【问题标题】:How do I create a request object in Django?如何在 Django 中创建请求对象?
【发布时间】:2011-01-07 01:28:13
【问题描述】:

所以我将 Django 与 Google App Engine 一起使用,并且我有一个 urls.py 文件,该文件将每个 url 重定向到相应的方法。这些方法中的每一个都作为参数之一自动传递“请求”,我相信这是一个 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

这似乎是错误的,因为我必须通过不需要它的函数传递请求,以便我可以在 baz 中使用它。

我想做这样的事情:

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

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

baz():
    request = HttpRequest()
    do something with request here

即如果我不需要,请不要传递请求。但是,做 request = HttpRequest() 返回一个空的请求对象...我想要的是一个完全填充的版本,就像从 urls.py 调用的每个方法中传递的一样。

我在这里浏览了 HttpRequest 的文档: http://docs.djangoproject.com/en/dev/ref/request-response/ 但没有看到方法。

任何想法将不胜感激。

谢谢, 瑞恩

【问题讨论】:

    标签: django google-app-engine request httprequest


    【解决方案1】:

    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 , ...)
    

    【讨论】:

      【解决方案2】:

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

      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
      

      见:Notes on Python variable scope

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

      【讨论】:

      • 抱歉,Lance,我认为我没有很好地解释原始帖子中的问题所在。我已经更新了它......希望现在更清楚了。
      • 我仍然认为这个问题与变量范围有关。我已更新我的答案以使用全局变量。
      • 谢谢兰斯。我的函数都在不同的 .py 文件中,我真的不想走使用全局变量的路线。
      • 看看我在上次编辑中链接到的另一个问题。如果您确实找到了更好的解决方案,请告诉我们。
      • 不是最漂亮的方法,但感谢链接对我有用。谢谢
      猜你喜欢
      • 1970-01-01
      • 2023-03-28
      • 2019-12-21
      • 1970-01-01
      • 1970-01-01
      • 2021-08-01
      • 2019-08-05
      • 2017-09-12
      • 2021-03-23
      相关资源
      最近更新 更多