title: Run while loop as background process in Flask app
body: <p>I'm looking to run a web server that reads a stream on <code>sys.stdin</code>. That reading needs to happen continuously, e.g. in a while loop.</p>
  
  <p>However, I'm also looking to run a Flask server that listens for requests to <code>/data</code> and sends the last bit of data read from <code>sys.stdin</code> to the requesting agent.</p>
  
  <p>So far I've found that my while loop is halting the execution of my app, which makes absolute sense. Here's my setup:</p>
  
  <pre><code>from flask import Flask, jsonify
  import sys
  
  # state
  frames = []
  frame = []
  
  while True:
    l = sys.stdin.readline()
    if 'end_frame' in l:
      frames = [frame] + frames
      frame = []
    elif l.rstrip('\n'):
      frame.append(l.rstrip('\n'))
  
  # app
  app = Flask(__name__, static_url_path='')
  
  @app.route('/frames')
  def get_frames():
    return jsonify(frames)
  
  app.run(host='0.0.0.0', port=5050)
  </code></pre>
  
  <p>Is there a way to run that <code>while</code> loop as a background process so as to free up the flask route listeners? Any suggestions would be helpful!</p>