Like many others, I've struggled with getting Pyramid to render JSON 
exceptions.  Thanks to a few recent updates to Pyramid and WebOb, things 
got a whole lot easier.

The new behavior allows for JSON to be generated based on the "accept" 
request headers.  Unfortunately, sending this header might not be possible 
(or easy) with low-level clients and utilities.  While testing some 
approaches, I came across the following trick:

    @view_config(context=HTTPException)
    def exception_view__upgrade(exc, request):
        """if we end with .json, serve json."""
        if (request.path[-5:]).lower() == '.json':
            request.environ['HTTP_ACCEPT'] = "application/json"
        return exc

I just used the `request.path` to ensure the test in 
`pyramid/httpexceptions.py` passes if a ".json" document is requested. 
 Depending on your needs, you may want to use another condition.  If you're 
already using a custom `context=HTTPException` view, this would need to be 
factored in.  This behavior works because of a few current implementation 
details on Pyramid, so it's not guaranteed to last... but for now it works 
and has saved me a lot of grief.


(i accidentally posted a version of this earlier with some code for 
customizing exceptions that wasn't properly abstracted out and didn't work 
outside my application. sorry if you saw that.)

-- 
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/6cfd1063-5545-4738-8c87-824741efd073%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to