Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

django.test.Client and response.content vs. streaming_content

I have a Django test that accesses a web page using the Django test client.

In one of the tests, the server returns a ZIP file as an attachment. I access the content of the ZIP file with the following code:

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

This causes the following deprecation warning:

D:/Developments/Archaeology/DB/ArtefactDatabase/Webserver\importexport\tests\test_import.py:1: DeprecationWarning: Accessing the content attribute on a streaming response is deprecated. Use the streaming_content attribute instead.`

response.streaming_content returns some sort of map, which is definitely not a file-like object that's required for ZipFile. How can I use the streaming_content attribute for this?

Incidentally, I only get the deprecation warning when passing response.content to a StringIO, when I access the response.content of an ordinary HTML page, there's no warning.

like image 310
zmbq Avatar asked Oct 01 '22 09:10

zmbq


1 Answers

Using Python 3.4.

with String:

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

with Bytes:

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

Solution found in TestStreamingMixin of https://github.com/sio2project/oioioi/blob/master/oioioi/filetracker/tests.py

See also: https://docs.djangoproject.com/en/1.7/ref/request-response/

You might want to test whether the response is a stream by checking response.streaming (boolean).

like image 181
Risadinha Avatar answered Oct 02 '22 23:10

Risadinha