django - 如何从 django-piston 处理程序中为 JSON 消息设置 HTTP header ?

标签 django django-piston

在活塞处理程序中,我需要将 django.db.models.query.QuerySet 作为正确的 JSON 消息返回(反射(reflect)底层模型和查询),同时还添加我自己的 HttpResponse header 。到目前为止,我可以做一个或另一个,但不能同时做这两个(并获得一个看起来合适的 JSON 响应)。

下面生成一个正确的 JSON 格式的响应,但没有添加 HttpResponse header (未显示):

class PollHandlerSearch(BaseHandler):
    allowed_methods = ('POST')
    model = Poll
    fields = ('id', 'question', 'pub_date')
    KEYS =  ( 'question', 'start-date', 'end-date' )

    def create(self, request):
        post = Poll.objects.all()
        for skey in self.KEYS:
            if len(post) and request.POST.has_key(skey) and len(request.POST[skey]):
                if skey == self.KEYS[0]:
                        post = post.filter(question__icontains=request.POST[skey])
                elif skey == self.KEYS[1]:
                        post = post.filter(pub_date__gte=request.POST[skey])
                elif skey == self.KEYS[2]:
                        post = post.filter(pub_date__lte=request.POST[skey])
        return post

生成格式正确的 JSON 消息:

[
    {
        "pub_date": "2010-08-23 22:15:07", 
        "question": "What's up?", 
        "id": 1
    }
]

下面使用添加的 header 实现一个 HttpResponse 并生成一个看起来像 JSON 的响应,但这不是预期或想要的,而且没有反射(reflect) django 的“DateTimeAwareJSONEncoder”所做的任何事情(由活塞的 JSONEmitter 使用)。

class PollHandlerSearch(BaseHandler):
    allowed_methods = ('POST')
    model = Poll
    fields = ('id', 'question', 'pub_date')
    KEYS =  ( 'question', 'start-date', 'end-date' )

    def create(self, request):
        resp = HttpResponse()
        post = Poll.objects.all()
        for skey in self.KEYS:
            if len(post) and request.POST.has_key(skey) and len(request.POST[skey]):
                if skey == self.KEYS[0]:
                        post = post.filter(question__icontains=request.POST[skey])
                elif skey == self.KEYS[1]:
                        post = post.filter(pub_date__gte=request.POST[skey])
                elif skey == self.KEYS[2]:
                        post = post.filter(pub_date__lte=request.POST[skey])
        json_serializer = serializers.get_serializer("json")()
        json_serializer.serialize(post, ensure_ascii=False, indent=4, stream=resp)
        resp['MYHEADER'] = 'abc123'
        return resp

导致格式不正确的 JSONish 消息:

[
    {
        "pk": 1, 
        "model": "polls.poll", 
        "fields": {
            "pub_date": "2010-08-23 22:15:07", 
            "question": "What's up?"
        }
    }
]

这毫无疑问会发生,因为我正在做我自己的 JSON 序列化,绕过活塞的 JSONEmitter 以及它为正确呈现“post”所做的任何事情。

我一直在研究 piston 的 emitters.py,但基本上跟不上它(我在 OOP/Python/django/piston 方面还是个新手)。我如何才能让 Piston 传送格式正确的 JSON 消息,其中包含 HTTP header 并辅以我提供的 header ?

最佳答案

您可以子类化 piston.resource.Resource,并在 __call__ 方法中添加您想要的任何 header 。 从活塞.resource 导入资源

class MyResource(Resource):
    def __call__(self, request, *args, **kwargs):
        resp = super(MyResource, self).__call__(request, *args, **kwargs)
        resp['HEADER'] = "abc123"
        return resp

然后,在你的 urls.py 中:

def BasicResource(handler):
    return resource.MyResource(handler=handler, authentication=basic)

your_handler = BasicResource(YourHandlerClass)
another_handler = BasicResource(AnotherHandlerClass)

关于django - 如何从 django-piston 处理程序中为 JSON 消息设置 HTTP header ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3656084/

相关文章:

django - virtualenv 返回错误 'Operation not Permitted'

python - 使用 Apache/NginX 部署 Django Bad Request(400) 错误

django - django-piston模块可以创建上传图像的restful webservice吗

python - 发布 django 时过滤 csrfmiddlewaretoken

python - Django 管理自定义按钮不起作用

python - 期望从 View 返回 `Response` 、 `HttpResponse` 或 `HttpStreamingResponse` ,但收到了 `<class ' NoneType'>`

django - Django 中的 query.clone()、queryset.clone() 是什么?

python - Django-piston:如何获得 app_label + model_name?

Python 连接到 Django 活塞

python - Django + SQLAlchemy + RESTful API(美味?)