django-jsonview
django-jsonview copied to clipboard
Add input parsing
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 - 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:
- application/x-www-form-urlencoded
- multipart/form-data
- 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.
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=Trueshould ignore the value of the content-type header, if any, and try to parse the request as JSON. (If the default value isTrue, thenassume_json=Falsewould 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 likeparse_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_responseand@json_response()would do the same thing.
@jsocol: Here's the pr: #32
@jsocol, Plese have a look at PR #32