Reputation: 11028
When I print a request object from a view function in views.py
I get a dictionary-like django.core.handlers.wsgi.WSGIRequest
object(inherits from django.http.HttpRequest
). Printing this dictionary-like object from a view function returns a bunch of values, especially for the META
key.
Now I'd like to call this same data from the manage.py shell
of my project but handlers
is not an attribute of django.core
in the shell so I cannot get the django.core.handlers.wsgi.WSGIRequest
object. Is there any way of getting the request object as in my view function but called from the manage.py shell
?
Upvotes: 0
Views: 916
Reputation: 7759
Since your goal is to "replicate a request object and fiddle with it from the shell for introspection", the easiest way to accomplish fiddling with the request object is to use a debugger.
Copy paste the following into your view and reload it:
import pdb; pdb.set_trace()
Now reload the page pointing at that view & you can use PDB's debugger commands to exec your stuff. For example, inside a view function you can use p request
to print the value of request, and you can also execute standard python code:
(Pdb) path = request.META['USERNAME']
(Pdb) h p
p expression
Print the value of the expression.
(Pdb) p path
'Caspar'
(Pdb) from foo.models import MyUser
(Pdb) MyUser.objects.all()
[<MyUser: Bob: 3.62810036125>, <MyUser: Tim: no rating>, <MyUser: Jim: 2.41014167534>, <MyUser: Rod: 1.35651839383>]
Even better, install ipdb
(pip install ipdb
), which lets you use the much nicer IPython shell, with fancy colors and tab completion.
Or, if you have no need for a debugger but just want an interactive console, install IPython (pip install ipython
) and use the following snippet:
import IPython; IPython.embed()
Note that IPython is a prerequisite for ipdb, so installing ipdb will also install IPython.
Upvotes: 1