3

在活塞处理程序中,我需要将 django.db.models.query.QuerySet 作为正确的 JSON 消息(反映底层模型和查询)返回,同时还添加我自己的 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 标头?

4

1 回答 1

3

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

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)
于 2011-01-28T01:46:25.383 回答