title: Generate and stream compressed file with Flask
body: <p>I am able to generate and stream text on the fly, but unable to generate and stream a compressed file on the fly.</p>
  
  <pre><code>from flask import Flask, request, Response,stream_with_context
  import zlib
  import gzip
  
  app = Flask(__name__)
  
  def generate_text():
      for x in range(10000):
          yield f"this is my line: {x}\n".encode()
  
  @app.route('/stream_text')
  def stream_text():
      response = Response(stream_with_context(generate_text()))
      return response
  
  def generate_zip():
      for x in range(10000):
          yield zlib.compress(f"this is my line: {x}\n".encode())
  
  @app.route('/stream_zip')
  def stream_zip():
      response = Response(stream_with_context(generate_zip()), mimetype='application/zip')
      response.headers['Content-Disposition'] = 'attachment; filename=data.gz'
      return response
  
  if __name__ == '__main__':
      app.run(host='0.0.0.0', port=8000, debug=True)
  </code></pre>
  
  <p>Than using curl and gunzip:</p>
  
  <pre><code>curl http://127.0.0.1:8000/stream_zip &gt; data.gz
  
  gunzip data.gz
  gunzip: data.gz: not in gzip format
  </code></pre>
  
  <p>I don't care if it is zip, gzip, or any other type of compression.</p>
  
  <p><code>generate_text</code> in my real code generates over 4 GB of data so I would like to compress on the fly.  </p>
  
  <p><strong>Saving text to file, zipping, returning zip file, and than deleting is not the solution I'm after.</strong></p>
  
  <p>I need to be in a loop generating some text -> compress that text -> streaming compressed data until I'm done. </p>
  
  <p>zip/gzip ... anything is fine as long as it works.</p>