Reputation: 9986
Does anyone know what's the 'best' way to move the meta information that gets returned with every request out to the http headers instead??
I was planning to do something like this:
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']
Any suggestions from someone that has already done something similar?
Upvotes: 1
Views: 160
Reputation: 9986
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.
Upvotes: 1
Reputation: 1898
If you mean move the meta information from the serialized data tastypie returns to the HTTP headers of the response, I think you'll need to override the create_reponse
method instead. You don't have an HttpResponse object available from alter_list_data_to_serialize
. Something like this should get you started:
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
Upvotes: 1