title: How to return chunked binary data in flask response?
body: <p>I have a flask endpoint handling get requests and I am interested in returning a list of objects (serialised) in a response, but in "chunked" way. By that, I mean that when I make a get request to that endpoint, I want to be able to iterate over the response (as if I am getting a list of binary data) and deserialise each "chunk" of into an object.</p>
  
  <p>I was able to achieve a result similar to my needs, but with strings. For example:</p>
  
  <p>Server side:</p>
  
  <pre class="lang-py prettyprint-override"><code>from flask import stream_with_context, request, Response
  
  from flask import Flask
  
  app = Flask(__name__)
  
  
  @app.route('/stream')
  def streamed_get():
      @stream_with_context
      def generate():
          yield 'Hello \n'
          yield "there\n"
          yield '!\n'
  
      return Response(generate())
  </code></pre>
  
  <p>Client side:</p>
  
  <pre class="lang-py prettyprint-override"><code>import requests
  
  response = requests.get("http://127.0.0.1:5000/stream", stream=True)
  for i in response.iter_lines():
      print(i)
  </code></pre>
  
  <p>That will print:</p>
  
  <pre><code>Hello 
  there
  !
  </code></pre>
  
  <p>But that seems obvious, since I am using <code>response.iter_lines()</code>. </p>
  
  <p>So to experiment further, I tried sending a post request to the server like this:</p>
  
  <p>Client side:</p>
  
  <pre class="lang-py prettyprint-override"><code>def gen():
      yield 'hi\n'
      yield 'there'
  
  
  requests.post("http://127.0.0.1:5000/stream_post", data=gen())
  </code></pre>
  
  <p>Server side:</p>
  
  <pre class="lang-py prettyprint-override"><code>@app.route('/stream_post',  methods=['POST'])
  def stream_post():
      count = 0
      for i in request.stream:
          print(i, count)
          count += 1
      print(request.data)
      return Response()
  </code></pre>
  
  <p>That prints on server console:</p>
  
  <pre><code>('hi\n', 0)
  ('there', 1)
  </code></pre>
  
  <p>What I don't know is how to do a similar thing but for a serialised object, for example. I feel like there is a fundamental gap in my knowledge, because it seems that I am looking for is a way of returning a chunk encoded response? Or at least some sort of response that would carry with it its size, so I can iterate over it on the client side, if that makes any sense.</p>