本文研究的主要是Flask實現異步非阻塞請求功能,具體實現如下。
最近做物聯網項目的時候需要搭建一個異步非阻塞的HTTP服務器,經過查找資料,發現可以使用gevent包。
關于gevent
Gevent 是一個 Python 并發網絡庫,它使用了基于 libevent 事件循環的 greenlet 來提供一個高級同步 API。下面是代碼示例:
1
2
3
4
5
|
from gevent.wsgi import WSGIServer from yourapplication import app http_server = WSGIServer(('', 5000 ), app) http_server.serve_forever() |
代碼清單
下面放上Flask異步非阻塞的代碼清單,以后需要用到的時候直接移植即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
# 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()這一條語句呢?在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實現異步非阻塞請求功能實例解析的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!
原文鏈接:http://blog.csdn.net/yannanxiu/article/details/52915929