Search code examples
djangoapirestdjango-piston

How to return a formated error message and the right HTTP code using django-piston?


I would like to be able to return a HTTP Reponse with a formated content with django-piston.

I guess I have to create my own rc_factory.

What I would like to do is :

return rc.404({'status': 0,'message': 'This restaurant does not exists.'})

With a result provide by XMLEmiter, JSONEmiter or YAMLEmiter regarding to the format the client is looking for.

How can I do that ?

Cheers


Solution

  • What do you think of somthing like this :

    # -*- coding: utf-8 -*-
    from piston.handler import typemapper
    from piston.emitters import Emitter
    
    def getErrorResponse(http_code, payload, em_format='json'):
            emitter, ct = Emitter.get(em_format)
            srl = emitter(payload, typemapper, handler=None, anonymous=False)
            r = srl.render({})
            return HttpResponse(r, content_type=ct, status=http_code)
    

    To use like this :

    return getErrorResponse(404, {'status': 0,'message': 'This restaurant does not exists.'})
    

    But the problem comes from the em_format attribute.

    Actually the hander method is able to get this information by adding the with the emitter_format attribute in the handler function.

    ...
        def read(self, request, emitter_format=None):
            if emitter_format is None:
                emitter_format = request.GET.get('format', 'json')
    
            ...
            return getErrorResponse(404, {'status': 0,'message': 'This restaurant does not exists.'}, emitter_format)