Created
August 28, 2017 15:59
-
-
Save pior/7052e8cf945b71549e9d3557b2c002b4 to your computer and use it in GitHub Desktop.
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
| def not_found_error(detail): | |
| error = {'id': 'not_found', 'detail': detail} | |
| return JSONApiObject(errors=[error]) | |
| class JSONApiObject: | |
| """Container for JSON API response.""" | |
| def __init__(self, data=None, errors=None): | |
| self.data = data | |
| self.errors = errors | |
| DESCRIBE_JSONAPI_FORMAT = {'name': 'jsonapi', 'schema_url': 'http://jsonapi.org/format/'} | |
| def jsonapi_adapter(payload, request): | |
| """Adapter to enforce a valid JSON API schema.""" | |
| response = {'meta': {'format': DESCRIBE_JSONAPI_FORMAT}} | |
| if payload.data: | |
| response['data'] = payload.data | |
| if payload.errors: | |
| response['errors'] = payload.errors | |
| return response | |
| def segment_adapter(segment, request): | |
| return { | |
| 'type': 'segments', | |
| 'id': segment.id, | |
| 'attributes': { | |
| 'key': segment.key.decode('utf-8'), | |
| }, | |
| 'links': { | |
| 'self': request.route_url('segments_show', id=segment.id), | |
| } | |
| } | |
| def setup_json_renderer(config): | |
| renderer = pyramid.renderers.JSON() | |
| def datetime_adapter(obj, request): | |
| return obj.isoformat() | |
| renderer.add_adapter(datetime.datetime, datetime_adapter) | |
| renderer.add_adapter(JSONApiObject, jsonapi_adapter) | |
| renderer.add_adapter(models.Segment, segment_adapter) | |
| config.add_renderer('json', renderer) | |
| def view_segments_index(request): | |
| segments = request.store.list_segments() | |
| return JSONApiObject([segment for segment in segments]) |
Author
Oh nice!
Is it safe to make json the default renderer? No corner cases?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
LGTM!
If needed, to add a default renderer:
Then, no need to specify a renderer on view config.