Skip to content

Instantly share code, notes, and snippets.

@bpeck
Last active February 15, 2016 15:00
Show Gist options
  • Save bpeck/594afdb19a33aedf8028 to your computer and use it in GitHub Desktop.
Save bpeck/594afdb19a33aedf8028 to your computer and use it in GitHub Desktop.
flask inside multiprocessing
import multiprocessing
import multiprocessing.queues
from flask import Flask
from flask import request
class Backend(object):
def __init__(self, command_queue, host='0.0.0.0', port=8000, debug=True):
self.command_queue = command_queue
self.flask_app = Flask('Backend')
self.flask_app.add_url_rule('/', "handleRequest", self.handleRequest, methods=['GET'])
self.flask_app.run(host=host, port=port, debug=debug, use_reloader=False)
def handleRequest(self):
for key in request.args.keys():
val = request.args.get(key, '')
ret += str(key) + " = " + str(val) + "<br>"
if request.method == 'POST':
ret += "<br>Request method is POST"
else:
ret += "<br>Request method is GET"
self.command_queue.put(request.args)
return ret
def _worker(command_queue):
print "Starting up web interface worker"
global backend_instance
if backend_instance == None:
backend_instance = Backend(command_queue)
def stop():
global backend_instance
print "Stopping web interface worker"
command_queue.empty()
web_backend_process.terminate()
backend_instance = None
def poll():
if backend_instance != None and not backend_instance.command_queue.empty():
return backend_instance.command_queue.get()
else:
return None
backend_instance = None
command_queue = multiprocessing.queues.SimpleQueue()
web_backend_process = multiprocessing.Process(None, _worker, \
"async web interface listener", [command_queue])
web_backend_process.start()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment