1

有谁知道将每个请求返回的元信息移动到 http 标头的“最佳”方法是什么?

我打算做这样的事情:

def alter_list_data_to_serialize(self,request,data_dict):
        if isinstance(data_dict,dict):
            if 'meta' in data_dict:
                # grab each property of the data_dict['meta'] 
                #and put it on the request headers
            if 'objects' in data_dict:
                return data_dict['objects']

已经做过类似事情的人有什么建议吗?

4

2 回答 2

1

In case anybody needs the same thing, this is how I was able to get it working... Thanks to GregM.

I created a class that inherits from tastypie ModelResource and made the adjustments to it. Then, all my resources use my class instead.

From his code, I just had to add a couple of try, except because when you GET a single item E.g. .../api/v1/user/2/ the meta doesn't exist and there is an AttributeError exception being thrown.

Then, you should be good to go.

class MyModelResource(ModelResource):
    def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
        try:
            stripped_data = data.get('objects')
        except AttributeError:
            stripped_data = data
        desired_format = self.determine_format(request)
        serialized = self.serialize(request, stripped_data, desired_format)
        response = response_class(content=serialized,
                                  content_type=build_content_type(desired_format),
                                  **response_kwargs)
        # Convert meta data to HTTP Headers
        try:
            for name, value in data.get('meta', {}).items():
                response['Meta-' + name.title().replace('_','-')] = str(value)
        except AttributeError:
            response['Meta-Empty'] = True
        return response

Again, full credit to Greg, thanks.

于 2013-08-20T01:06:20.477 回答
1

如果您的意思是将元信息从美味派返回的序列化数据中移动到响应的 HTTP 标头中,我认为您需要重写该create_reponse方法。您没有可用的 HttpResponse 对象alter_list_data_to_serialize。这样的事情应该让你开始:

def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
    stripped_data = data.get('objects') or data
    desired_format = self.determine_format(request)
    serialized = self.serialize(request, stripped_data, desired_format)
    response = response_class(content=serialized,
                              content_type=build_content_type(desired_format),
                              **response_kwargs)
    # Convert meta data to HTTP Headers 
    for name, value in data.get('meta', {}).items():
        response[name] = str(value)
    return response
于 2013-08-19T18:12:59.403 回答