http.StreamingHttpResponse

class StreamingHttpResponse [source]

The StreamingHttpResponse class is used to stream a response from Django to the browser. You might want to do this if generating the response takes too long or uses too much memory. For instance, it’s useful for generating large CSV files.

Performance considerations

Django is designed for short-lived requests. Streaming responses will tie a worker process for the entire duration of the response. This may result in poor performance.

Generally speaking, you should perform expensive tasks outside of the request-response cycle, rather than resorting to a streamed response.

The StreamingHttpResponse is not a subclass of HttpResponse, because it features a slightly different API. However, it is almost identical, with the following notable differences:

  • It should be given an iterator that yields strings as content.
  • You cannot access its content, except by iterating the response object itself. This should only occur when the response is returned to the client.
  • It has no content attribute. Instead, it has a streaming_content attribute.
  • You cannot use the file-like object tell() or write() methods. Doing so will raise an exception.

StreamingHttpResponse should only be used in situations where it is absolutely required that the whole content isn’t iterated before transferring the data to the client. Because the content can’t be accessed, many middlewares can’t function normally. For example the ETag and Content-Length headers can’t be generated for streaming responses.

doc_Django
2016-10-09 18:38:57
Comments
Leave a Comment

Please login to continue.