flask async response

python 2017. 1. 4. 12:05

Gevent monkey patch makes requests to react asynchronous.

Environment: mac OS 10.11.5, python 3.5.2, gevent==1.1.2, requests==2.12.4

Example:

from flask import Flask

from gevent.pywsgi import WSGIServer
from gevent import monkey

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

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


@app.route('/test')
def test(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://www.google.com'
app.logger.debug('started %d', request_num)
rsp = requests.get(url)
app.logger.debug('finish %d', request_num)

return rsp.text


def main():
http = WSGIServer(('', 5000), app.wsgi_app)
http.serve_forever()


if __name__ == '__main__':
main()

Result:

started 1

started 2

started 3

started 4

started 5

started 6

finish 4

finish 5

finish 3

finish 6

finish 1

finish 2

'python' 카테고리의 다른 글

websocket with gunicorn  (0) 2017.03.03
gunicorn vs uwsgi  (0) 2017.01.20
functools.wraps에 대해  (0) 2015.04.15
Apple Push Notification Service(APNs) python modules  (0) 2015.04.07
Getting specific timezone timestamp from time string  (0) 2015.01.20
블로그 이미지

시간을 거스르는자

,