Last active
December 29, 2015 15:08
-
-
Save siteshen/7688169 to your computer and use it in GitHub Desktop.
A Mixin for Django and JSend specification. Tornado version: https://gist.github.com/siteshen/6612013
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class JSendMixin(object): | |
| """http://labs.omniti.com/labs/jsend | |
| JSend is a specification that lays down some rules for how JSON | |
| responses from web servers should be formatted. | |
| JSend focuses on application-level (as opposed to protocol- or | |
| transport-level) messaging which makes it ideal for use in | |
| REST-style applications and APIs. | |
| """ | |
| def render_to_response(self, context, **response_kwargs): | |
| """ | |
| Returns a JSON response, transforming 'context' to make the payload. | |
| """ | |
| response_kwargs['content_type'] = 'application/json' | |
| return HttpResponse(json.dumps(context), **response_kwargs) | |
| def success(self, data, **response_kwargs): | |
| """When an API call is successful, the JSend object is used as a simple | |
| envelope for the results, using the data key. | |
| """ | |
| return self.render_to_response( | |
| {'status': 'success', 'data': data}, **response_kwargs) | |
| def fail(self, data, **response_kwargs): | |
| """There was a problem with the data submitted, or some pre-condition | |
| of the API call wasn't satisfied. | |
| """ | |
| return self.render_to_response( | |
| {'status': 'fail', 'data': data}, **response_kwargs) | |
| def error(self, message, data=None, code=None, **response_kwargs): | |
| """An error occurred in processing the request, i.e. an exception was | |
| thrown. | |
| """ | |
| result = {'status': 'error', 'message': message} | |
| if data: | |
| result['data'] = data | |
| if code: | |
| result['code'] = code | |
| return self.render_to_response(result, **response_kwargs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment