django.test.Client和response.content与streaming_content的区别

9 投票
2 回答
3498 浏览
提问于 2025-04-18 12:27

我有一个Django测试,它使用Django测试客户端来访问一个网页。

在其中一个测试中,服务器返回了一个ZIP文件作为附件。我用以下代码来获取这个ZIP文件的内容:

zip_content = StringIO(response.content)
zip = ZipFile(zip_content)

这段代码引发了一个弃用警告:

D:/Developments/Archaeology/DB/ArtefactDatabase/Webserver\importexport\tests\test_import.py:1: DeprecationWarning: 访问流响应的content属性已被弃用。请改用streaming_content属性。

response.streaming_content返回的是某种映射,这显然不是ZipFile所需要的文件样式对象。我该如何使用streaming_content属性呢?

顺便提一下,只有在将response.content传递给StringIO时,我才会收到这个弃用警告;当我访问普通HTML页面的response.content时,就没有警告。

2 个回答

-3

你应该改变一下测试的方法。response.streaming_content 正在按预期工作。你只需要测试一下下载的调用是否正常就可以了。

如果你想测试文件的生成或完整性,那就需要单独测试这些功能。无论你的文件是ZIP格式还是CSV格式,对Django测试来说都没关系,关键是你调用这个功能是否正常。

9

使用的是 Python 3.4。

处理字符串时:

zip_content = io.StringIO("".join(response.streaming_content))
zip = ZipFile(zip_content)

处理字节时:

zip_content = io.BytesIO(b"".join(response.streaming_content))
zip = ZipFile(zip_content)

解决方案可以在 https://github.com/sio2project/oioioi/blob/master/oioioi/filetracker/tests.py 的 TestStreamingMixin 中找到。

另外,你可以查看: https://docs.djangoproject.com/en/1.7/ref/request-response/

你可能想通过检查 response.streaming(布尔值)来测试响应是否是一个流。

撰写回答