python - Flask and subprocess Popen - Send same data to multiple users -


the code below need. when second user connect, new subprocess.popen created, need run 1 subprocess.popen , send same data multiple users.

example: first user connect, start subprocess.popen, begins receive result starting number 0, when second user connect 30 seconds after, begins receive result starting de number 30.

#!/usr/bin/env python import os functools import partial subprocess import popen, pipe  flask import flask, response  # $ pip install flask  file = 'test.file' app = flask(__name__)   @app.route('/' + file) def stream():     process = popen([ "bash", "-c", "for ((i=0;i<100;i=i+1)); echo $i; sleep 1; done" ], stdout=pipe, bufsize=-1)     read_chunk = partial(os.read, process.stdout.fileno(), 1024)     return response(iter(read_chunk, b''), mimetype='audio/mp3')  if __name__ == "__main__":     app.run(host='0.0.0.0',threaded=true) 

to honest not sure if work. not use subprocess module much, not sure if appropriate use case. question in general reminds me of flask extensions.

i trying suggest use similar pattern flask extensions...

  1. check if resource exists
  2. if not, create it
  3. return it

store on flask global, api recommendation extension development.

edit: realized route file name changed keys reflect that

#!/usr/bin/env python import os functools import partial subprocess import popen, pipe flask import flask, response, _app_ctx_stack stack  file = 'test.file' app = flask(__name__)  def get_chunk(file):     ctx = stack.top     key = "read_chunk_%s" % file     if ctx not none:         if not hasattr(ctx, key):             process = popen(["bash", "-c", "for ((i=0;i<100;i=i+1)); echo $i; sleep 1; done"],                              stdout=pipe, bufsize=-1)             setattr(ctx, key, partial(os.read, process.stdout.fileno(), 1024))         return getattr(ctx, key)   @app.route('/' + file) def stream():     read_chunk = get_chunk(file)     return response(iter(read_chunk, b''), mimetype='audio/mp3')  if __name__ == "__main__":     app.run(host='0.0.0.0',threaded=true) 

Comments

Popular posts from this blog

php - Vagrant up error - Uncaught Reflection Exception: Class DOMDocument does not exist -

vue.js - Create hooks for automated testing -

Add new key value to json node in java -