On Tue, Sep 29, 2009 at 9:14 PM, Chris <crso...@googlemail.com> wrote:
>
> Hi
>
> We are creating a web service using Pyons that uses XML as the primary
> response content type. We have had some trouble when using abort()
> because it raises a webob.exc.WSGIHTTPException which has a HTML
> response as it's default body.
>
> The workaround we have implemented overrides _inspect_call() in
> base.py like this
>
> def _inspect_call(self, func):
>    result = super(BaseController, self)._inspect_call(func)
>    if hasattr(result,'empty_body'):
>        result.empty_body = True
>
>    return result
>
>
> Perhaps it should be the default to always set empty_body to True when
> a WSGIHTTPException is raised or when it is caught.

I've made a json_abort function to raise customized webob.exc in my lib/util.py:

import simplejson as json

def json_abort(status_code=None, detail="", headers=None, comment=None):
    """Same with pylons.controllers.util.abort but with json output."""

    exc_class = status_map[status_code]
    class JsonException(exc_class):
        def __call__(self, environ, start_response):
            self.content_type = 'text/javascript; charset=utf-8'
            self.body = json.dumps(self.detail)
            return Response.__call__(self, environ, start_response)
    exc = JsonException(detail=detail, headers=headers, comment=comment)

    log.debug("Aborting request with JSON response, status: %s,
detail: %r, headers: %r, "
              "comment: %r", status_code, detail, headers, comment)
    request.environ['pylons.status_code_redirect'] = True  # skip err doc
    raise exc.exception

so that, I can just call json_abort(404, {'reason': "resource not
found"}) in my controllers and users will receive a 404 error response
with a json documenting the reason in it.


-- 
Qiangning Hong
http://www.douban.com/people/hongqn/

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups 
"pylons-devel" group.
To post to this group, send email to pylons-devel@googlegroups.com
To unsubscribe from this group, send email to 
pylons-devel+unsubscr...@googlegroups.com
For more options, visit this group at 
http://groups.google.com/group/pylons-devel?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to