Flask-Flask实现异步非阻塞请求功能 debug功能 timeout功能

http://blog.csdn.net/yannanxiu/article/details/52915929

前言

最近做物联网项目的时候需要搭建一个异步非阻塞的HTTP服务器,经过查找资料,发现可以使用gevent包。

关于gevent

Gevent 是一个 Python 并发网络库,它使用了基于 libevent 事件循环的 greenlet 来提供一个高级同步 API。下面是代码示例:

 

from gevent.wsgi import WSGIServer
from yourapplication import app

http_server = WSGIServer(('', 5000), app)
http_server.serve_forever()

 

代码清单

下面放上Flask异步非阻塞的代码清单,以后需要用到的时候直接移植即可。

 

# 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

 

 

 

 

注意:如果要实现timeout功能呢,比如一个请求时间太长,就杀死

class MyServer(pywsgi.WSGIServer):

  def handle(self, socket, address):
    socket.settimeout(<your timeout>)
    return pywsgi.WSGIServer.handle(self, socket, address)

if __name__ == "__main__":
    # app.run()
    http_server = MyServer(('', 5000), app)
    http_server.serve_forever()


分享到: 微信 更多