Skip to content
Myr

document using gevent for async

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 4f79d5b · Browse files · 9 files+168 added−142 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

9 files+168 added−142 removed

  • other:+168 added−142 removed

9 files+168 added−142 removed

modified:docs/deploying/eventlet.rst+4 added-76 removed
1:orphan:23eventlet4========54Prefer using :doc:`gunicorn` with eventlet workers rather than using5`eventlet`_ directly. Gunicorn provides a much more configurable and6production-tested server.6`Eventlet is no longer maintained.`__ Use :doc:`/deploying/gevent` instead.78`eventlet`_ allows writing asynchronous, coroutine-based code that looks9like standard synchronous Python. It uses `greenlet`_ to enable task10switching without writing ``async/await`` or using ``asyncio``.1112:doc:`gevent` is another library that does the same thing. Certain13dependencies you have, or other considerations, may affect which of the14two you choose to use.1516eventlet provides a WSGI server that can handle many connections at once17instead of one per worker process. You must actually use eventlet in18your own code to see any benefit to using the server.1920.. _eventlet: https://eventlet.net/21.. _greenlet: https://greenlet.readthedocs.io/en/latest/222324Installing25----------2627When using eventlet, greenlet>=1.0 is required, otherwise context locals28such as ``request`` will not work as expected. When using PyPy,29PyPy>=7.3.7 is required.3031Create a virtualenv, install your application, then install32``eventlet``.3334.. code-block:: text3536 $ cd hello-app37 $ python -m venv .venv38 $ . .venv/bin/activate39 $ pip install . # install your application40 $ pip install eventlet414243Running44-------4546To use eventlet to serve your application, write a script that imports47its ``wsgi.server``, as well as your app or app factory.4849.. code-block:: python50 :caption: ``wsgi.py``5152 import eventlet53 from eventlet import wsgi54 from hello import create_app5556 app = create_app()57 wsgi.server(eventlet.listen(("127.0.0.1", 8000)), app)5859.. code-block:: text6061 $ python wsgi.py62 (x) wsgi starting up on http://127.0.0.1:8000636465Binding Externally66------------------6768eventlet should not be run as root because it would cause your69application code to run as root, which is not secure. However, this70means it will not be possible to bind to port 80 or 443. Instead, a71reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used72in front of eventlet.7374You can bind to all external IPs on a non-privileged port by using75``0.0.0.0`` in the server arguments shown in the previous section.76Don't do this when using a reverse proxy setup, otherwise it will be77possible to bypass the proxy.7879``0.0.0.0`` is not a valid address to navigate to, you'd use a specific80IP address in your browser.8__ https://eventlet.readthedocs.io
modified:docs/deploying/gevent.rst+5 added-9 removed
5 unmodified lines
6configurable and production-tested servers.78`gevent`_ allows writing asynchronous, coroutine-based code that looks9like standard synchronous Python. It uses `greenlet`_ to enable task10switching without writing ``async/await`` or using ``asyncio``.10switching without writing ``async/await`` or using ``asyncio``. This is11not the same as Python's ``async/await``, or the ASGI server spec.1212:doc:`eventlet` is another library that does the same thing. Certain13dependencies you have, or other considerations, may affect which of the14two you choose to use.1513gevent provides a WSGI server that can handle many connections at once17instead of one per worker process. You must actually use gevent in your18own code to see any benefit to using the server.14instead of one per worker process. See :doc:`/gevent` for more15information about enabling it in your application.1617.. _gevent: https://www.gevent.org/18.. _greenlet: https://greenlet.readthedocs.io/en/latest/192021Installing22----------2327When using gevent, greenlet>=1.0 is required, otherwise context locals28such as ``request`` will not work as expected. When using PyPy,24When using gevent, greenlet>=1.0 is required. When using PyPy,25PyPy>=7.3.7 is required.2627Create a virtualenv, install your application, then install ``gevent``.28
48 unmodified lines
modified:docs/deploying/gunicorn.rst+11 added-25 removed
6 unmodified lines
7* It tends to integrate easily with hosting platforms.8* It does not support Windows (but does run on WSL).9* It is easy to install as it does not require additional dependencies10 or compilation.11* It has built-in async worker support using gevent or eventlet.11* It has built-in async worker support using gevent.1213This page outlines the basics of running Gunicorn. Be sure to read its14`documentation`_ and use ``gunicorn --help`` to understand what features15are available.
76 unmodified lines
92``0.0.0.0`` is not a valid address to navigate to, you'd use a specific93IP address in your browser.949596Async with gevent or eventlet97-----------------------------96Async with gevent97-----------------9899The default sync worker is appropriate for many use cases. If you need100asynchronous support, Gunicorn provides workers using either `gevent`_101or `eventlet`_. This is not the same as Python's ``async/await``, or the102ASGI server spec. You must actually use gevent/eventlet in your own code103to see any benefit to using the workers.99The default sync worker is appropriate for most use cases. If you need numerous,100long running, concurrent connections, Gunicorn provides an asynchronous worker101using `gevent`_. This is not the same as Python's ``async/await``, or the ASGI102server spec. See :doc:`/gevent` for more information about enabling it in your103application.104105When using either gevent or eventlet, greenlet>=1.0 is required,106otherwise context locals such as ``request`` will not work as expected.107When using PyPy, PyPy>=7.3.7 is required.105.. _gevent: https://www.gevent.org/106109To use gevent:107When using gevent, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is108required.109110.. code-block:: text111112 $ gunicorn -k gevent 'hello:create_app()'113 Starting gunicorn 20.1.0114 Listening at: http://127.0.0.1:8000 (x)115 Using worker: gevent116 Booting worker with pid: x118119To use eventlet:120121.. code-block:: text122123 $ gunicorn -k eventlet 'hello:create_app()'124 Starting gunicorn 20.1.0125 Listening at: http://127.0.0.1:8000 (x)126 Using worker: eventlet127 Booting worker with pid: x128129.. _gevent: https://www.gevent.org/130.. _eventlet: https://eventlet.net/
modified:docs/deploying/index.rst-1 removed
34 unmodified lines
35 waitress36 mod_wsgi37 uwsgi38 gevent39 eventlet39 asgi4041WSGI servers have HTTP servers built-in. However, a dedicated HTTP42server may be safer, more efficient, or more capable. Putting an HTTP
36 unmodified lines
modified:docs/deploying/uwsgi.rst+9 added-11 removed
117 unmodified lines
118119Async with gevent120-----------------121122The default sync worker is appropriate for many use cases. If you need123asynchronous support, uWSGI provides a `gevent`_ worker. This is not the124same as Python's ``async/await``, or the ASGI server spec. You must125actually use gevent in your own code to see any benefit to using the126worker.122The default sync worker is appropriate for most use cases. If you need numerous,123long running, concurrent connections, uWSGI provides an asynchronous worker124using `gevent`_. This is not the same as Python's ``async/await``, or the ASGI125server spec. See :doc:`/gevent` for more information about enabling it in your126application.127128When using gevent, greenlet>=1.0 is required, otherwise context locals129such as ``request`` will not work as expected. When using PyPy,130PyPy>=7.3.7 is required.128.. _gevent: https://www.gevent.org/129130When using gevent, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is131required.132133.. code-block:: text134135 $ uwsgi --http 127.0.0.1:8000 --master --gevent 100 -w wsgi:app136
3 unmodified lines
140 spawned uWSGI master process (pid: x)141 spawned uWSGI worker 1 (pid: x, cores: 100)142 spawned uWSGI http 1 (pid: x)143 *** running gevent loop engine [addr:x] ***143144145.. _gevent: https://www.gevent.org/
modified:docs/async-await.rst+11 added-17 removed
21 unmodified lines
22method in views that inherit from the :class:`flask.views.View` class, as23well as all the HTTP method handlers in views that inherit from the24:class:`flask.views.MethodView` class.2526.. admonition:: Using ``async`` with greenlet2628 When using gevent or eventlet to serve an application or patch the29 runtime, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is30 required.313227Performance28-----------2930Async functions require an event loop to run. Flask, as a WSGI
40 unmodified lines
71Flask based on the `ASGI`_ standard instead of WSGI. This allows it to72handle many concurrent requests, long running requests, and websockets73without requiring multiple worker processes or threads.7481It has also already been possible to run Flask with Gevent or Eventlet82to get many of the benefits of async request handling. These libraries83patch low-level Python functions to accomplish this, whereas ``async``/84``await`` and ASGI use standard, modern Python capabilities. Deciding85whether you should use Flask, Quart, or something else is ultimately up86to understanding the specific needs of your project.75It has also already been possible to :doc:`run Flask with Gevent </gevent>` to76get many of the benefits of async request handling. Gevent patches low-level77Python functions to accomplish this, whereas ``async``/``await`` and ASGI use78standard, modern Python capabilities. Deciding whether you should use gevent79with Flask, or Quart, or something else is ultimately up to understanding the80specific needs of your project.8188.. _Quart: https://github.com/pallets/quart89.. _ASGI: https://asgi.readthedocs.io/en/latest/82.. _Quart: https://quart.palletsprojects.com83.. _ASGI: https://asgi.readthedocs.io848586Extensions87----------
25 unmodified lines
113114Other event loops115-----------------116123At the moment Flask only supports :mod:`asyncio`. It's possible to124override :meth:`flask.Flask.ensure_sync` to change how async functions125are wrapped to use a different library.117At the moment Flask only supports :mod:`asyncio`. It's possible to override118:meth:`flask.Flask.ensure_sync` to change how async functions are wrapped to use119a different library. See :ref:`gevent-asyncio` for an example.
added:docs/gevent.rst+125 added
1Async with Gevent2=================34`Gevent`_ patches Python's standard library to run within special async workers5called `greenlets`_. Gevent has existed since long before Python's native6asyncio was available, and Flask has always worked with it.78.. _gevent: https://www.gevent.org9.. _greenlets: https://greenlet.readthedocs.io1011Gevent is a reliable way to handle numerous, long lived, concurrent connections,12and to achieve similar capabilities to ASGI and asyncio. This works without13needing to write ``async def`` or ``await`` anywhere, but relies on gevent and14greenlet's low level manipulation of the Python interpreter.1516Deciding whether you should use gevent with Flask, or `Quart`_, or something17else, is ultimately up to understanding the specific needs of your project.1819.. _quart: https://quart.palletsprojects.com202122Enabling gevent23---------------2425You need to apply gevent's patching as early as possible in your code. This26enables gevent's underlying event loop and converts many Python internals to run27inside it. Add the following at the top of your project's module or top28``__init__.py``:2930.. code-block:: python3132 import gevent.monkey33 gevent.monkey.patch_all()3435When deploying in production, use :doc:`/deploying/gunicorn` or36:doc:`/deploying/uwsgi` with a gevent worker, as described on those pages.3738To run concurrent tasks within your own code, such as views, use39|gevent.spawn|_:4041.. |gevent.spawn| replace:: ``gevent.spawn()``42.. _gevent.spawn: https://www.gevent.org/api/gevent.html#gevent.spawn4344.. code-block:: python4546 @app.post("/send")47 def send_email():48 gevent.spawn(email.send, to="example@example.example", text="example")49 return "Email is being sent."5051If you need to access :data:`request` or other Flask context globals within the52spawned function, decorate the function with :func:`.stream_with_context` or53:func:`.copy_current_request_context`. Prefer passing the exact data you need54when spawning the function, rather than using the decorators.5556.. note::5758 When using gevent, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.759 is required.606162.. _gevent-asyncio:6364Combining with ``async``/``await``65----------------------------------6667Gevent's patching does not interact well with Flask's built-in asyncio support.68If you want to use Gevent and asyncio in the same app, you'll need to override69:meth:`flask.Flask.async_to_sync` to run async functions inside gevent.7071.. code-block:: python7273 import gevent.monkey74 gevent.monkey.patch_all()7576 import asyncio77 from flask import Flask, request7879 loop = asyncio.EventLoop()80 gevent.spawn(loop.run_forever)8182 class GeventFlask(Flask):83 def async_to_sync(self, func):84 def run(*args, **kwargs):85 coro = func(*args, **kwargs)86 future = asyncio.run_coroutine_threadsafe(coro, loop)87 return future.result()8889 return run9091 app = GeventFlask(__name__)9293 @app.get("/")94 async def greet():95 await asyncio.sleep(1)96 return f"Hello, {request.args.get("name", "World")}!"9798This starts an asyncio event loop in a gevent worker. Async functions are99scheduled on that event loop. This may still have limitations, and may need to100be modified further when using other asyncio implementations.101102103libuv104~~~~~105106`libuv`_ is another event loop implementation that `gevent supports`_. There's107also a project called `uvloop`_ that enables libuv in asyncio. If you want to108use libuv, use gevent's support, not uvloop. It may be possible to further109modify the ``async_to_sync`` code from the previous section to work with uvloop,110but that's not currently known.111112.. _libuv: https://libuv.org/113.. _gevent supports: https://www.gevent.org/loop_impls.html114.. _uvloop: https://uvloop.readthedocs.io/115116To enable gevent's libuv support, add the following at the *very* top of your117code, before ``gevent.monkey.patch_all()``:118119.. code-block:: python120121 import gevent122 gevent.config.loop = "libuv"123124 import gevent.monkey125 gevent.monkey.patch_all()
modified:docs/index.rst+1 added
59 unmodified lines
60 shell61 patterns/index62 web-security63 deploying/index64 gevent65 async-await666768API Reference
22 unmodified lines
modified:docs/installation.rst+2 added-3 removed
49 unmodified lines
5051greenlet52~~~~~~~~5354You may choose to use gevent or eventlet with your application. In this55case, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is56required.54You may choose to use :doc:`/gevent` with your application. In this case,55greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is required.5657These are not minimum supported versions, they only indicate the first58versions that added necessary features. You should use the latest59versions of each.
84 unmodified lines