本文研究的主要是Flask實現異步非阻塞請求功能,具體實現如下。
最近做物聯網項目的時候需要搭建一個異步非阻塞的HTTP服務器,經過查找資料,發現可以使用gevent包。
Gevent 是一個Python 並發網絡庫,它使用了基於libevent 事件循環的greenlet 來提供一個高級同步API。下面是代碼示例:
from gevent.wsgi import WSGIServerfrom yourapplication import apphttp_server = WSGIServer(('', 5000), app)http_server.serve_forever()下面放上Flask異步非阻塞的代碼清單,以後需要用到的時候直接移植即可。
# coding=utf-8# Python Version: 3.5.1# Flaskfrom flask import Flask, request, g# geventfrom gevent import monkeyfrom gevent.pywsgi import WSGIServermonkey.patch_all()# gevent endimport timeapp = 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()這一條語句呢?在gevnet的官網有詳細的解釋,這裡簡單說明一下:
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
以上就是本文關於Flask實現異步非阻塞請求功能實例解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!