How to manipulate the response object in a django piston?

I have some existing python code that uses django-piston which returns a dictionary as an answer. For instance:

from piston.handler import BaseHandler

class FooHandler(BaseHandler):
    allowed_methods = ('GET',)

    @classmethod
    def create(self, request):
        return { 'foo': 'bar' }

This code works fine and is serialized in JSON with the appropriate set of HTTP headers (I assume it works with some kind of piston magic involving emitters, for bonus points feel free to clarify how this works, as I'm still recognizing the django piston )

I need to be able to modify the answer in arbitrary ways, for example. installation headers, status codes, etc., without using any pre-baked solution designed for a specific purpose. Is there a convenient way to access the response object in the context of this code and manipulate it, or is the response object not yet created? To access the response object, I will have to manually create it (a la vanilla django), serialize the dictionary and set the corresponding headers manually and, thus, play some of the useful magic of the django piston

+3
source share
3 answers

Each django-piston method returns an HTTPResponse.

, django-piston HTTPResponse, .

, , "return rc.CREATED" django-piston - HTTP .

: https://bitbucket.org/jespern/django-piston/src/c4b2d21db51a/piston/utils.py

rc_factory, HTTPResponse Piston.

, , , .

" HTTPResponse" - , . , -.

+1

, HttpResponse .

return HttpResponse({'foo': 'bar'}, status=404)

, . , . - :

class CustomEmitter(JSONEmitter):
    def render(self, request):
        content = super(CustomEmitter, self).render(request)
        response = HttpResponse(content)
        response['Cache-Control'] = 'max-age=60'

Emitter.register('json', CustomEmitter, 'application/json; charset=utf-8')
+1

, django-piston / . .

, .

1. mime-type
2. <format> in your URL
3. .json at the end of your URL

? , .

0

Source: https://habr.com/ru/post/1763927/


All Articles