How to create a request object in Django?

So, I am using Django with the Google App Engine, and I have a urls.py file that redirects each URL to the corresponding method. Each of these methods is automatically passed a “request” as one of the arguments, which, in my opinion, is an HttpRequest object.

How to create this filled request object from my code? For example, if I am inside a method deep inside my code, I would like to access this request object without passing it to each function to make sure that it is available. Assuming urls.py calls the foo method, the way I'm doing it right now 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 need to pass the request through functions that it doesn’t need, so that I have it in baz.

I would 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. Do not miss the request if I do not need it. However, executing the request = HttpRequest () returns an empty request object ... what I want is a fully populated version, for example, that is passed to each method called with urls.py.

I looked at the documentation for HttpRequest here: http://docs.djangoproject.com/en/dev/ref/request-response/ but did not see how to do this.

Any thoughts would be greatly appreciated.

Thanks Ryan

+6
google-app-engine django request
source share
2 answers

Just create a query variable in front of the view definitions and set its value when you get it from the view (using the 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: Python Variable Area Notes

Update: This question is very similar to yours, and the decision made basically creates a global query variable and binds it to the settings.

0
source share

request = HttpRequest() will give you an empty one, but you can write something.

Here is an example that I used in my project:

 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 , ...) 
+1
source share

All Articles