Drill down to flask's asynchronous non blocking implementation code example
- 2020-11-26 18:50:49
- OfStack
In fact, the official has given the plan, but it is a little hidden, in addition to the Internet there are a lot of unreliable posts misled me (of course, I do not exclude the reason that I did not understand). So to keep some of your friends from taking detours, keep a memo for yourself.
Complete code: https: / / github com wskssau/my_notespace python/todo_app
Solution: flask+gevent
Install gevent
pip install gevent
Modify the code
# The file header
from gevent import monkey
from gevent.pywsgi import WSGIServer
# In the play websockets Can ignore the ha, free post next flask websockets To achieve the
from geventwebsocket.handler import WebSocketHandler
import time
# gevent Monkey magic
monkey.patch_all()
app = Flask(__name__)
app.config.update(
DEBUG=True
)
@app.route('/asyn/1/', methods=['GET'])
def test_asyn_one():
if request.method == 'GET':
time.sleep(10)
return 'hello asyn'
@app.route('/test/', methods=['GET'])
def test():
return 'hello test'
if __name__ == "__main__":
# app.run()
http_server = WSGIServer(('', 5000), app, handler_class=WebSocketHandler)
http_server.serve_forever()
After running, /asyn/1/ can be accessed first and then /test/, and it is obvious that /asyn/1/ will not affect other requests while doing time-consuming tasks