Python

[Flask] 异步非阻塞IO实现

2018-08-16  本文已影响1070人  _小老虎_

Flask默认是不支持非阻塞IO的,表现为:

请求1未完成之前,请求2是需要等待处理状态,效率非常低。
在flask中非阻塞实现可以由2种:
# 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个

其中使用了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()
上一篇下一篇

猜你喜欢

热点阅读