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

时间:2010-09-07 05:51:19

标签: django django-piston

在活塞处理程序中,我需要返回一个django.db.models.query.QuerySet作为正确的JSON消息(反映underly模型和查询),同时还添加了我自己的HttpResponse头。到目前为止,我可以做其中一个,但不能两个(并获得正确的JSON响应)。

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

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
    }
]

下面实现了一个带有添加标题的HttpResponse,并生成一个JSONish看起来的响应,但不是预期或想要的响应,加上没有反映任何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'。

我一直在倾注活塞的emitters.py,并且很大程度上无法遵循它(我在OOP / Python / django /活塞中很新)。我怎样才能让活塞传递格式正确的JSON消息,其中HTTP标头补充了我提供的标题?

1 个答案:

答案 0 :(得分:3)

您可以继承piston.resource.Resource,并在__call__方法中添加所需的标头。     来自piston.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)