2013-04-18 61 views
1

我在Django開發中頗爲新穎。我有一個資源和型號:Django Tastypie添加內容長度標頭

型號

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

而且我請求所有的玩家/ API/V1 /播放/格式= xml,但似乎應答頭:Content-Length缺失,導致我的應用中出現一些問題。我如何將它添加到響應頭中?

非常感謝。

回答

3

缺乏的Content-Length的是,由於缺乏一箇中間件。
欲瞭解更多信息: 看吧:How do I get the content length of a Django response object?

但是你可以手動添加的內容長度是這樣的:

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 
2

您可以通過重寫create_reponse方法在自己的資源爲前加Content-Length頭:

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) 
相關問題