10

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")
Régis B.
  • 10,092
  • 6
  • 54
  • 90
Esquilax
  • 101
  • 1
  • 6
  • For python 2.7 and django 1.8 the above only returns the first line. but this will return all of the content: "".join([x for x in response.streaming_content]) – oden Aug 09 '15 at 04:56
  • is this one is relevant? http://stackoverflow.com/questions/35647476/django-streaminghttpresponse-format-error – yanik Feb 26 '16 at 10:12
  • Indeed, the proposed solution is "not very elegant" :). No need to cast to `list` (see my answer). – Régis B. May 20 '17 at 12:53

1 Answers1

14

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)
Régis B.
  • 10,092
  • 6
  • 54
  • 90