django-jsonview icon indicating copy to clipboard operation
django-jsonview copied to clipboard

Add input parsing

Open jsocol opened this issue 9 years ago • 4 comments

A simple decorator that would do something like this:

# POST {"foo": "bar"}
@json_request
def my_view(request):
    assert request.META['CONTENT_TYPE'] == 'application/json'
    assert request.data == {'foo': 'bar'}

Not 100% sure how to handle other content-types yet. That's probably got to go into some sort of setting. Do you always want to assume JSON (e.g. try to parse it regardless of the content-type header) or respect the header? If it does respect the header, does it make sense to assign request.data = request.POST if content-type is set to application/x-www-form-urlencoded? What's the right error-handling if you can't parse JSON (or form-encoded)? 400?

jsocol avatar May 28 '16 22:05 jsocol

@jsocol - The error HTTP status code should be 415 UNSUPPORTED MEDIA TYPE (see description)

The most commonly used content-types to send data in a request are:

  1. application/x-www-form-urlencoded
  2. multipart/form-data
  3. application/json

I can give a pull request to add decorator json_request, which will handle these cases and consider other cases as UNSUPPORTED MEDIA TYPE.

nitinbhojwani avatar Aug 23 '16 10:08 nitinbhojwani

Thanks @nitinbhojwani, I'd love to see that PR. A couple of thoughts ahead of time:

  • I'm not sure what the default behavior should be, but a param to the decorator like assume_json=True should ignore the value of the content-type header, if any, and try to parse the request as JSON. (If the default value is True, then assume_json=False would make it default to following the content-type header.)
  • I think your list of content-type values to support is right.
  • 415 is a good default but it should definitely be overrideable. It's important that users who are moving to @json_response() are able to maintain their current API responses. Maybe a kwarg like parse_error=415, and can be set to other values.
  • Ideally the decorator would work without () if the caller just wanted the defaults. I.e. @json_response and @json_response() would do the same thing.

jsocol avatar Aug 23 '16 12:08 jsocol

@jsocol: Here's the pr: #32

nitinbhojwani avatar Aug 25 '16 12:08 nitinbhojwani

@jsocol, Plese have a look at PR #32

nitinbhojwani avatar Mar 26 '17 18:03 nitinbhojwani