I am trying to run multiple flask apps(by creating various instances on different ports) on different greenlets on the same process. Each flask basically is supposed to shut itself down after a succesful POST request.
So, Is it even possible to run multiple Flask apps as multiple greenlets in a single process. I cannot seem to make it work.
I tried the following code.
from flask import Flask, request
import gevent
def func1(port):
app = Flask(__name__)
@app.route('/', methods=['POST'])
def choose_name():
func = request.environ.get('werkzeug.server.shutdown')
if func is None:
raise RuntimeError('Not running with the Werkzeug Server')
func()
return('done')
app.run(host='0.0.0.0', port=port)
t1=gevent.spawn(func1, 50001)
t2=gevent.spawn(func1, 50002)
gevent.joinall([t1,t2])
When I run this code, a server is started in port 50001 first and when it shuts down only after that a new server is started on 50002 port.
So is it even possible to run them concurrently using gevents.
I also tried the WSGIserver from gevents.pywsgi as you can see in the code below:
from flask import Flask, request
import gevent
from gevent.pywsgi import WSGIServer
def func1(port):
global http
app = Flask(__name__)
http = WSGIServer(('', port), app)
@app.route('/', methods=['POST'])
def choose_name():
global http
http.stop()
http.close()
return('done')
http.serve_forever()
t1=gevent.spawn(func1, 50001)
t2=gevent.spawn(func1, 50002)
gevent.joinall([t1,t2])
In this code I get very erratic behaviour, at first both the servers are running but after I do a request to any of the two servers, the one running on 50002 is closed but the one running on 50001 keeps running forever and can't be closed even after multiple requests.
Any help regarding flask or gevents is appreciated.