Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating the streaming_content attribute on django FileResponse

I'm working on an api with django rest framework, and I'm writing some unit tests to check critical operations. I'm trying to read the contents of a file after doing a get request

downloaded_file = self.client.get(textfile)

The problem is that the object returned is of type: django.http.response.FileResponse which inherits from StreamingHttpResponse.

I'm trying to iterate over the streaming_content attribute, which supposedly is an iterator, but I cannot iterate, no method next().

I inspected this object and what i get is map object. Any ideas on how to get the content from this request?

Edit:

Problem Solved

The returned object is a map, a map takes a function and a iterable:

https://docs.python.org/3.4/library/functions.html#map

What I had to do was to cast the map to a list, access the first element of the list and convert from bytes to string. Not very elegant but it works.

list(response.streaming_content)[0].decode("utf-8")
like image 451
Esquilax Avatar asked Apr 24 '15 19:04

Esquilax


1 Answers

Here is how you extract the content from a streaming_content map:

content = downloaded_file.getvalue()

Looking at the code of the getvalue() method, we see that it just iterates over the answer content:

class StreamingHttpResponse(HttpResponseBase):
    ...
    def getvalue(self):
        return b''.join(self.streaming_content)
like image 194
Régis B. Avatar answered Nov 08 '22 16:11

Régis B.