views:

19

answers:

1

Hello,

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

A: 

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)
Natim
I had to change something in `piston` to be able to get the `emitter_format` in the `read` method and now the emitter_format has to be define as a parameter in all my `read` method.
Natim