python 使用gevent在Flask中进行异步请求

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 使用gevent在Flask中进行异步请求相关的知识,希望对你有一定的参考价值。

"""Asynchronous requests in Flask with gevent"""

from time import time

from flask import Flask, Response

from gevent.pywsgi import WSGIServer
from gevent import monkey

import requests

# need to patch sockets to make requests async
monkey.patch_all()

CHUNK_SIZE = 1024*1024  # bytes

app = Flask(__name__)  # pylint: disable=invalid-name
app.debug = True


@app.route('/Seattle.jpg')
def seattle(requests_counter=[0]):  # pylint: disable=dangerous-default-value
    """Asynchronous non-blocking streaming of relatively large (14.5MB) JPG
    of Seattle from wikimedia commons.
    """
    requests_counter[0] += 1
    request_num = requests_counter[0]
    url = 'http://upload.wikimedia.org/wikipedia/commons/3/39/Seattle_3.jpg'

    app.logger.debug('started %d', request_num)

    rsp = requests.get(url, stream=True)

    def generator():
        "streaming generator logging the end of request processing"
        yield ''  # to make greenlet switch
        for data in rsp.iter_content(CHUNK_SIZE):
            yield data
        app.logger.debug('finished %d', request_num)

    return Response(generator(), mimetype='image/jpeg')


def main():
    "Start gevent WSGI server"
    # use gevent WSGI server instead of the Flask
    http = WSGIServer(('', 5000), app.wsgi_app)
    # TODO gracefully handle shutdown
    http.serve_forever()


if __name__ == '__main__':
    main()

以上是关于python 使用gevent在Flask中进行异步请求的主要内容,如果未能解决你的问题,请参考以下文章

Flask + Nginx + Gunicorn + Gevent部署

Flask-SocketIO 未使用 Gevent/Gevent-websocket

如何通过gevent使用Flask(uWSGI 和Gunicorn 版本)

python-flask复习——- flask请求上下文源码解读http聊天室单聊/群聊(基于gevent-websocket)

Flask, Tornado, GEvent组合运行与性能比较

gunicorn+gevent 怎么觉得未实现 flask 的真正并行