Automatic request parser decorator for JSON/XML format

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

Hi Genarito,

Your English is nothing to apologise for!

I’ve never worked on Django’s internals, but I do use Django Rest Framework a lot for working with JSON. It’s a sensation when it comes to JSON and serialising your models.

https://www.django-rest-framework.org/

I believe it also can work well with XML

https://www.django-rest-framework.org/api-guide/renderers/#xml

And let me apologise if you were already aware of DRF. Just thought I’d mention it in case you hadn’t had the pleasure to work with it.

Cheers,

C

2 Likes

Hi Conor! First of all, thank you for answering! Secondly, I’ve worked with DRF and It’s an excelent tool. I didn’t know the existence of JSONP, I’ll give a try!

Anyway I think that It would be nice to have a simpler solution, a Django’s decorator would be easier to use, avoiding import a new dependency to the project or set a middleware.