Hi, I’ve worked with Django for several months and I haven’t see a quick way to parse a request’s body which can be in JSON o XML format. Until now I’ve had to do:
import json
def some_view(request):
if request.content_type == 'application/json':
data = json.loads(request.body)
# Uses 'data' variable as we can't set parsed data to request.body
else:
# Uses request.POST[...], or request.GET[...], etc
In cases where It’s expected to have multiple formats (an application which uses JQuery will send the request in application/x-www-form-urlencoded
format, modern apps will send in json, and so on) it would be very cool to have a Django’s decorator to parse automatically especified formats and HTTP methods and set it to the request’s body to work with request.POST/GET/etc
as a QueryDict
instance.
The usage would be something like this:
from django.http import parse_request
@parse_request(['json', 'xml'], ['POST', 'GET', 'PATCH'])
def some_view(request):
field = request.POST['field']
What do you think about it? Would you like me to make a PR with this new decorator?
Thanks in advance and sorry about my English