python - Django Tastypie 添加 Content-Length header

标签 python django rest httpresponse tastypie

我是 Django 开发的新手。我有一个资源和模型:

型号

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

模型资源

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/player/?format=xml 但似乎缺少响应 header :Content-Length,这会导致我的应用程序出现一些问题。如何将它添加到响应 header 中?

非常感谢。

最佳答案

缺少 Content-Length 是因为缺少中间件。
了解更多信息 : 看这里:How do I get the content length of a Django response object?

但是您可以像这样手动添加 Content-Length :

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

关于python - Django Tastypie 添加 Content-Length header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16085185/

相关文章:

python - 使用 ReportLab 处理大型 PDF 所需的时间呈指数级增长

java - REST API 调用中的身份验证 header

python - 带有 nginx 反向代理的 django SECURE_SSL_REDIRECT

python - 在抛出断言 IntegrityError 的单元测试后进行清理

django - 如何从刷新数据库中恢复 South

javascript - 获取 API 请求的输出(客户端)

c - 使用 Ulfius 实现 REST API - URI 定义

python - 针对一维列表绘制单行二维 numpy 数组

python - Sklearn 模型 (Python) 与 NodeJS (Express) : how to connect both?

python - 将 Django 项目推送到 Heroku 时出错