前言
最近做物联网项目的时候需要搭建一个异步非阻塞的HTTP服务器,经过查找资料,发现可以使用gevent包。
代码清单
下面放上代码清单,以后需要用到的时候直接移植即可。
# 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()
测试
打开浏览器,首先请求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
参考资料