【Flask】Flask實現非同步非阻塞請求功能
阿新 • • 發佈:2018-12-30
前言
最近做物聯網專案的時候需要搭建一個非同步非阻塞的HTTP伺服器,經過查詢資料,發現可以使用gevent包。
關於gevent
Gevent 是一個 Python 併發網路庫,它使用了基於 libevent 事件迴圈的 greenlet 來提供一個高階同步 API。下面是程式碼示例:
from gevent.wsgi import WSGIServer
from yourapplication import app
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
程式碼清單
下面放上Flask非同步非阻塞的程式碼清單,以後需要用到的時候直接移植即可。
# coding=utf-8
# Python Version: 3.5.1
# Flask
from flask import Flask, request, g
# gevent
from gevent import monkey
from gevent.pywsgi import WSGIServer
monkey.patch_all()
# gevent end
import time
app = Flask(__name__)
app.config.update(DEBUG=True)
@app.route('/asyn/', methods=['GET'])
def test_asyn_one ():
print("asyn has a request!")
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)
http_server.serve_forever()
關於monkey.patch_all()
為什麼要加monkey.patch_all()
monkey carefully replace functions and classes in the standard socket module with their cooperative counterparts. That way even the modules that are unaware of gevent can benefit from running in a multi-greenlet environment.
翻譯:猴子補丁仔細的用並行程式碼副本替換標準socket模組的函式和類,這種方式可以使模組在不知情的情況下讓gevent更好的運行於multi-greenlet環境中。
測試
開啟瀏覽器,首先請求http://127.0.0.1:5000/asyn/
,然後
再請求http://127.0.0.1:5000/test/
這個介面十次。如果是一般的Flask框架,後面的介面是沒有響應的。
列印內容如下:
asyn has a request!
127.0.0.1 - - [2016-10-24 20:45:10] "GET /test/ HTTP/1.1" 200 126 0.000000
127.0.0.1 - - [2016-10-24 20:45:11] "GET /test/ HTTP/1.1" 200 126 0.000000
127.0.0.1 - - [2016-10-24 20:45:11] "GET /test/ HTTP/1.1" 200 126 0.000000
127.0.0.1 - - [2016-10-24 20:45:12] "GET /test/ HTTP/1.1" 200 126 0.000000
127.0.0.1 - - [2016-10-24 20:45:12] "GET /test/ HTTP/1.1" 200 126 0.000998
127.0.0.1 - - [2016-10-24 20:45:13] "GET /test/ HTTP/1.1" 200 126 0.001001
127.0.0.1 - - [2016-10-24 20:45:14] "GET /test/ HTTP/1.1" 200 126 0.000000
127.0.0.1 - - [2016-10-24 20:45:14] "GET /test/ HTTP/1.1" 200 126 0.001014
127.0.0.1 - - [2016-10-24 20:45:15] "GET /test/ HTTP/1.1" 200 126 0.001000
127.0.0.1 - - [2016-10-24 20:45:15] "GET /test/ HTTP/1.1" 200 126 0.000000
127.0.0.1 - - [2016-10-24 20:45:18] "GET /asyn/ HTTP/1.1" 200 126 10.000392