How do you see what an http request contains - django

I'm using a django framework for my assignment. I need to view what an http request object contains. print(request) is obviously not working. If I can see the object like in a json structure it would've been a huge help to understand what it would look like and what are the values it contains.

The best way to see what request contains (and more to that - any other object in python) is to use simple:
print(request.__dict__)

Depending on what type of request is GET or POST. You can find print(request.GET) or in print(request.POST) which is of <type 'dict'> and you can access data simply by request.GET.get("somedata") will return None if not found
Note: If you want to see attributes of request object you can do print(dir(request)) and you can do that on any object.
For more quick help you can do help(request) in python shell.

Related

django class view access response

in function view:
def view(request):
# do something with request
response = render(request, 'view.html')
# do something with response
return response
but now I have a View class:
class ArticleDeleteView(View):
pass
# or even something more complicated
class ArticleDeleteView(LoginRequiredMixin, UserPassesTestMixin, DeleteView):
pass
which function shall I overwrite to access to the response?
sorry that it may seems a silly question to you, but I looked through the docs and failed to find an answer.
thanks for all suggestions in comment. here's why I need to access to the response. Conditional Django Middleware (or how to exclude the Admin System)
I am building a specific type of 'middleware', for certain class based view, they are not actually middleware since they are not called for each request. I need to access to the response in order to do something before and after the response then return it, therefore I much would like to know which function generate response.
The easiest answer is: you don't. The View classes tend to be uncomplicated enough to be easily rewritten as a custom view which inherently gives you access to the response.
However if you insist I guess one of the functions you could override is the following: as_view, dispatch or setup as the request function goes through all of them. Sadly I couldn't find any mention of the one that was intended for that purpose.

How to GET the query parameters in Django-Tastypie

I am building a REST API for my application using Tastypie.
I've gone through this thread , but it didnt worked.
Actually, I want to pass a parameter to this method through the url (something like http://127.0.0.1:8000/api/v1/shipments/140119758884542/pptl_id/?DSP=1 ) and then perform a query based on this parameter.
The problem is that I can't get its parameter !
When printing the bundle variable, I see this :
<Bundle for obj: 'Shipment object' and with data: '{}'>
When printing kwargs variabl, I see this
{'pk': u'140119758884542/pptl_id'}
How do I get the query parameters?
Thanks for your help
Django's request object is kept in the bundle under the property named request.
You can use:
bundle.request.GET
in order to access the query parameters.
See documentation on the request document here

Tastypie - Get list of objects being editted (PUT/PATCH)

I am trying to do authorization in away that only owners of the objects can edit them.
How can i get the ids of the objects being edited in the post call in my authorization method?
Eg: If someone PUTs to the url /api/v1/resource_name/1, I want to get '1'
Also, tastypie allows a collection of objects to be edited at one go. (http://django-tastypie.readthedocs.org/en/latest/interacting.html#updating-a-whole-collection-of-resources-put)
Is there a way for me to get a list of the objects being edited in any call?
Thanks!
I have been struggling with this as well. Right now, I determine the object by parsing request.path. I believe a more direct method (via the object parameter in Authorization() for example) will become available in 0.9.12 and beyond.
You might watch this question as well: How can I pass a detail object to custom authorization in tastypie?.
Good luck.

How to display data resulting from POST in django view?

I have a form that takes a path as input, analyzes files and subfolders in that directory, stores information in a database, then displays some statistics to the user about the files just parsed. This is done currently using a Django view and render_to_response.
According to everything I have read, it's incorrect to use anything other that HttpResponseRedirect when dealing with a POST, as a page generated with POST data would resubmit the form if the page were refreshed.
My issue here is that there's a large amount of summary data ultimately displayed as a result of analyzing files on the provided path. How can I display that data with an httpResponseRedirect? Sending it as GET parameters using django.core.urlresolvers.reverse seems infeasible due to the amount of data.
You could put the data on request.session
http://www.djangobook.com/en/beta/chapter12/#cn36
http://docs.djangoproject.com/en/1.2/topics/http/sessions/
I assume that your POST handle creates some databse object out of a submitted form data, is this correct? If so, then you can do something like this (:
my_obj = MyModel.objects.create(**form.cleaned_data) # This is the part yuo already have, most probably expressed with some other code, but still..
return HttpResponseRedirect('/url/to/redirect/?id=%d' % obj.id)
The redirect like should in fact use reverse() function, and I think that you should have an URL for editing MyModel objects. Then you could do:
return HttpResponseRedirect(reverse('edit-mymodel', (), {'id': obj.id}))
The relevant URL would look like:
url('^edit/mymodel/(?P<id>\d+)$', 'apps.myapp', name='edit-mymodel')
A rough but simple solution is to write your data in a json text file and then read it in your redirect page (this will also save you from rebuilding data on refreshing the page)

How to manipulate the response object in django-piston?

I have some existing python code that uses django-piston which returns a dictionary as its response. For example:
from piston.handler import BaseHandler
class FooHandler(BaseHandler):
allowed_methods = ('GET',)
#classmethod
def create(self, request):
return { 'foo': 'bar' }
This code works fine, and is serialized into JSON with the appropriate HTTP header set (I'm assuming this works by some piston magic involving emitters; for bonus points, feel free to clarify how this behavior works as well, as I'm still getting to know django-piston).
I need to be able to modify the response in arbitrary ways, e.g. setting headers, status codes, etc. without using some pre-baked solution designed for a specific purpose. Is there a convenient way to access the response object in the context of this code and manipulate it, or has the response object not yet been created? In order to get access to a response object, will I have to construct it manually (a la vanilla django), serialize the dictionary, and set the appropriate headers by hand, and thus lose out on some of the useful magic of django-piston?
Every django-piston method returns an HTTPResponse.
When you return that dictionary, django-piston is just serializing it and sticking it in an HTTPResponse that it has crafted of some variety.
Kind of surprised you didn't pick up on that given that those "return rc.CREATED" lines in all the django-piston examples in the wiki are just hyper-simplistic responses with an HTTP code and response body.
Take a look here: https://bitbucket.org/jespern/django-piston/src/c4b2d21db51a/piston/utils.py
at the rc_factory class, which creates a variety of simple HTTPResponse objects for use with Piston.
At the very least you can observe how they do it, and then craft your own.
But the answer to the essence of your question "can I make a custom HTTPResponse" is yes, you can. Of course, that's what web servers do.
It is possible to set a custom response code by returning an HttpResponse object from your handler methods.
return HttpResponse({'foo': 'bar'}, status=404)
Unfortunately, you cannot set headers in the same way. For this, you have to write a custom Emitter that sets the headers you need. Something along these lines might work:
class CustomEmitter(JSONEmitter):
def render(self, request):
content = super(CustomEmitter, self).render(request)
response = HttpResponse(content)
response['Cache-Control'] = 'max-age=60'
Emitter.register('json', CustomEmitter, 'application/json; charset=utf-8')
You are quite right that django-piston uses emitters to serialize/deserialize requests and responses. You can even register your own emitters with piston and have it use those.
There are several ways that you can determine what the format should be.
1. mime-type
2. <format> in your URL
3. .json at the end of your URL
Which particular headers are you wanting to manipulate? There may be other solutions then just hacking away at the response object.