2

What is the correct way to stream JSON response from Django? E.g. use 'StreamingHttpResponse` for the following:

def sample_json_view(self):

    data = { ... }

    resp = http.HttpResponse(content_type="application/json")
    json.dump(data, resp)
    return resp

My goal is to use StreamingHttpResponse to minimize the latency in the view. Does StreamingHttpResponse offer benefit over HttpResponse where we are writing?

Or: Does writing to file-like HttpResponse object (like with json.dump) make Django / mod_wsgi to buffer the whole response on the server before starting to stream the response to the client? (increasing latency, all JSON response must be generated first).

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435

1 Answers1

-1

This depends on how your data is being generated, and if you need the content rendered before all of the data is generated. The Django docs seem to discourage this, saying "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."

For an example of how to correctly use StreamingHttpResponse, see Django 1.5 - using the new StreamingHttpResponse

Community
  • 1
  • 1
Aaron H
  • 159
  • 1
  • 4