MaT
MaT

Reputation: 1606

Django Tastypie add Content-Length header

I am quite new in Django development. I have a Resource and Model:

Model

class Player(models.Model):
    pseudo = models.CharField(max_length=32, unique=True)

ModelResource

class PlayerResource(ModelResource):
    class Meta:
        queryset = Player.objects.all()
        resource_name = 'player'
        authentication = BasicAuthentication()
        authorization = Authorization()
        serializer = Serializer(formats=['xml'])
        filtering = {
            'pseudo': ALL,
        }

And I am requesting all the players with /api/v1/player/?format=xml but it seems that the response header : Content-Length is missing which causes some issues in my app. How can I add it in the response header ?

Thanks a lot.

Upvotes: 1

Views: 1582

Answers (2)

MaT
MaT

Reputation: 1606

The lack of Content-Length was due to the lack of a Middleware.
For more information : Look here : How do I get the content length of a Django response object?

But you can manually add the Content-Length like this :

def create_response(self, request, data, response_class=HttpResponse, **response_kwargs):
        desired_format = self.determine_format(request)
        serialized = self.serialize(request, data, desired_format)
        response = response_class(content=serialized, content_type=build_content_type(desired_format), **response_kwargs)
        response['Content-Length'] = len(response.content)
        return response

Upvotes: 3

UnLiMiTeD
UnLiMiTeD

Reputation: 1040

You can add Content-Length header by overriding create_reponse method in your own resource for ex:

class MyResource(ModelResource):
   class Meta:
        queryset=MyModel.objects.all()

   def create_response(self, ...)
      # Here goes regular code that do the method from tastypie
      return response_class(content=serialized, content_type=build_content_type(desired_format), Content-Length=value,  **response_kwargs)

Upvotes: 2

Related Questions