Travis
Travis

Reputation: 4078

How to return an object with non-200 status code with django-piston?

In my django-piston handler functions, it looks like I can basically do two things. Either I can return a specific status code with some non-formatted content:

def create(...):
    ...    
    resp = rc.BAD_REQUEST
    resp.content = 'Some string error message'
    return resp

Or I can return a dictionary of error messsages, which can be formatted according to the specified emitter, but with a 200 status code:

def create(...):
    ...
    return error_dict

How can I return a dictionary or model object, formatted by the specified emitter, but with a customized status code?

Upvotes: 1

Views: 560

Answers (2)

mollocampo
mollocampo

Reputation: 41

How about this?

def create(...):
    ...    
    resp = rc.BAD_REQUEST
    resp.content = error_dict
    return resp

Upvotes: 4

Travis
Travis

Reputation: 4078

In order to solve this, I added a new function to the my subclass of the BaseHandler, although it could just be added to any handler. The function manually calls the emitter to properly format the content, then adds the content-type and status code.

class MyBaseHandler(BaseHandler):

    def render_response(self, request, response, content):

        em_info = None
        for ext in Emitter.EMITTERS:
            if request.path.find('.'+ext) > -1:
                em_info = Emitter.get(ext)
        if not em_info:
            return rc.NOT_FOUND

        RequestEmitter = em_info[0]

        emitter = RequestEmitter(content, typemapper, self, self.fields, False)
        response.content = emitter.render(request)
        response['Content-Type'] = em_info[1]

        return response

Called like so:

def create(...):
    ... 
    return self.render_response(request, rc.BAD_REQUEST, error_dict)

Upvotes: 1

Related Questions