Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add input parsing #28

Open
jsocol opened this issue May 28, 2016 · 4 comments
Open

Add input parsing #28

jsocol opened this issue May 28, 2016 · 4 comments
Milestone

Comments

@jsocol
Copy link
Owner

jsocol commented May 28, 2016

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?

@nitinbhojwani
Copy link

@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.

@jsocol
Copy link
Owner Author

jsocol commented Aug 23, 2016

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.

@nitinbhojwani
Copy link

@jsocol: Here's the pr: #32

@nitinbhojwani
Copy link

@jsocol, Plese have a look at PR #32

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants