A mixin that attempts to parse the request as JSON. If request is properly formatted, the json is saved to self.request_json as a Python object.
I'm somewhat new to contributing and testing, so I'd welcome any feedback on this pull request. I wrote tests for this mixin and it's marked as having full coverage, so that's something, I suppose. Still, I'd appreciate it if someone could look over the tests I wrote and tell me if I'm doing something stupid.
I wanted this mixin to be as unobtrusive as possible - you can add this to a view without it affecting anything; it just provides a request_json attribute and a HTTP400 "Bad Request" response (but you'll have to call it yourself). Also, since this Mixin inherits from JSONResponseMixin, perhaps "JsonRequestMixin" is a bit of a misnomer (as it also gives access to the response methods).
If the request cannot be turned into JSON, request_json becomes None. This allows you to check for failure (request_json is None), failure or empty requests (not request_json), or ignore it altogether. I thought about putting in more API features (in particular, a method to get_or_400 from the JSON would be nice), but I thought it made sense to have a minimum functionality version first without imposing too rigid a structure.
What do you guys think about the utility of this mixin? I recently needed to parse JSON requests and had no idea how. It's pretty simple, but I think this makes it simpler. Are there more features I should add? Better ways to implement these features?
working, documented, and tested JsonRequestMixin
I like this. I wonder if it shouldn't be renamed to JSONRequestResponseMixin, though.
I can change the mixin name. What do you think of error handling? I'm trying to find the balance between making stuff work out of the box and not taking too much control. Errors parsing bad JSON should register as 400 errors, not 500. Here are some things I'm thinking about putting in:
I'm worried about feature creep though, it's just a mixin, not a full JSON API library. Are either or both of those worth putting in? What's more in line with braces' use cases?
get_or_400 seems like overkill. We already have KeyError exceptions that fit this perfectly.
I think the require_json attribute is a good idea, though.
Okay, I'll write that up and change the name. Thanks for the input!
If you can get these changes in soon, and make sure it's tested, we can get this into 1.3
Changed name to JsonRequestResponseMixin and added require_json flag
merging JsonRequestMixin stuff with latest changes
changed to JsonRequestResponseMixin and added require_json flag
Okay, I think that should be everything. Let me know if you see any mistakes or omissions.