Flask默认是不支持非阻塞IO
的,表现为:
当 请求1
未完成之前,请求2
是需要等待处理状态,效率非常低。
在flask中非阻塞实现可以由2种:
- 启用flask多线程机制
# Flask
from flask import Flask, request, g
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
app = Flask(__name__)
app.config.update(DEBUG=True)
#获取本机电脑名
myname = socket.getfqdn(socket.gethostname( ))
#获取本机ip
myaddr = socket.gethostbyname(myname)
myport = 8912
@app.route('/test1')
def the_test1():
print "test1 print start"
time.sleep(10)
print "test1 print after sleep"
return 'hello asyn'
@app.route('/test2')
def the_test2():
print "test2 print!"
return 'test2 return'
if __name__ == '__main__':
app.run(host=myaddr,port=myport,debug=False,threaded=True) ### threaded开启以后 不需要等队列 threaded=True
#或者
#app.run(host=myaddr,port=myport,debug=False,processes=3) ### processes=N 进程数量,默认为1个
- 启用monkey模块socket支持
其中使用了Gevent 是一个 Python 并发网络库,它使用了基于libevent 事件循环的 greenlet 来提供一个高级同步 API。下面是代码示例:
from gevent.wsgi import WSGIServer
from yourapplication import app
http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()
# Flask
from flask import Flask, request, g
import os
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
# gevent
from gevent import monkey
from gevent.pywsgi import WSGIServer
monkey.patch_all()
# gevent end
app = Flask(__name__)
app.config.update(DEBUG=True)
#获取本机电脑名
myname = socket.getfqdn(socket.gethostname( ))
#获取本机ip
myaddr = socket.gethostbyname(myname)
myport = 8912
@app.route('/test1')
def the_test1():
print "test1 print start"
time.sleep(10)
print "test1 print after sleep"
return 'hello asyn'
@app.route('/test2')
def the_test2():
print "test2 print!"
return 'test2 return'
if __name__ == '__main__':
http_server = WSGIServer((myaddr, myport), app)
http_server.serve_forever()