A few people, myself included, have struggled with this in the past. While
some recent PRs in webob and pyramid will adjust a response if
"application/json" is in the HTTP_ACCEPT environment, I've run into a few
situations where low-level clients don't (easily) have the ability to
specify this
Playing around, I figured out a somewhat streamlined way to handle this
situation using 2 exception views:
1. use a "dispatch" route to upgrade the response, to take advantage of
recent Pyramid features
2. optional - add a custom json renderer to tweak the content as needed
Example code is below:
@view_config(context=HTTPException)
def exception_view__dispatch(exc, request):
"""if we end with .json, serve json.
the decision could be made by any request method/attribute"""
if (request.path[-5:]).lower() == '.json':
request.environ['HTTP_ACCEPT'] = "application/json"
return exc
return exc
@view_config(context=HTTPException, renderer='json',
accept="application/json")
def exception_view__JSON(exc, request):
"""This view will generate a custom json error"""
rval = {'error': exc.message,
'status_code': None,
}
if exc.status_code is not None:
request.response.status_code = exc.status_code
rval['status_code'] = exc.status_code
return rval
--
You received this message because you are subscribed to the Google Groups
"pylons-discuss" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To post to this group, send email to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/pylons-discuss/92cce682-4a19-4882-9073-4559100cb14d%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.