Search code examples
djangogoogle-app-enginerequesthttprequest

How do I create a request object in Django?


So I'm using Django with Google App Engine and I have an urls.py file that redirects each url to a corresponding method. Each one of those methods is automatically passed "request" as one of the arguments, which I believe is an HttpRequest object.

How do I create this populated request object from within my code? For example, if I'm within some method deep within my code, I'd like to have access to this request object without having to pass it to every function to make sure it's available. Assuming urls.py calls the method foo, the way I'm currently doing it is:

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

This seems wrong because I'm having to pass request through functions that don't need it just so that I have it available in baz.

I'd like to do something like:

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

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

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

i.e. not pass request around if I don't have to. However, doing request = HttpRequest() returns an empty request object...what I want is a fully populated version, like what is passed into each method called from urls.py.

I glanced through the documentation for HttpRequest here: http://docs.djangoproject.com/en/dev/ref/request-response/ but didn't see the way to do it.

Any thoughts would be greatly appreciated.

Thanks, Ryan


Solution

  • Just create a request variable before the view definitions and set its value when you receive it from the view (using your example code):

    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
    

    See: Notes on Python variable scope

    Update: This question is very similar to yours and the accepted solution is basically creating a global request variable and attaching it to the settings.