Include Content-disposition header for Django FileUpload

丶灬走出姿态 提交于 2019-12-10 14:57:35

问题


I defined an API endpoint which accepts a file (e.g. using Django REST Framework). In Django, the content disposition header can be used when inspecting the response.

https://docs.djangoproject.com/en/1.11/ref/request-response/#telling-the-browser-to-treat-the-response-as-a-file-attachment

Now, if we want to set the header when testing the endpoint, how do I include this header using REST-Framework's APITestCase?

What I tried so far is, but it does not seem to accept the headers.

class TestSaleViews(APITestCase):
    def test_sale_detail_view(self):
        f = create_named_temporary_file()
        files = {'archive': f}
        basename = os.path.basename(f.name)
        headers = {
            'content-disposition': 'attachment; filename={}'.format(basename),
        }
        response = self.client.post(url, files, format='multipart', **headers)

回答1:


Found the answer!

Django has a fixed keyword for this header in its FileUploadParser. It is: HTTP_CONTENT_DISPOSITION

So I needed to replace it et voila: worked!

headers = {
  'HTTP_CONTENT_DISPOSITION': 'attachment; filename={}'.format(basename),
}

https://github.com/encode/django-rest-framework/blob/master/rest_framework/parsers.py#L206



来源:https://stackoverflow.com/questions/44244553/include-content-disposition-header-for-django-fileupload

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!