document using gevent for async (#5900)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by GitHub · parents 4f79d5b, ac5664d · 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
Provenance
- Commit
407eb76- Tree
30b1f72- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
4f79d5b- Parent 2
ac5664d
9 files changed+168 added−142 removed
modified:docs/deploying/eventlet.rst+4 added-76 removed
1+:orphan:2+3 eventlet4 ========5 4-Prefer using :doc:`gunicorn` with eventlet workers rather than using5-`eventlet`_ directly. Gunicorn provides a much more configurable and6-production-tested server.6+`Eventlet is no longer maintained.`__ Use :doc:`/deploying/gevent` instead.7 8-`eventlet`_ allows writing asynchronous, coroutine-based code that looks9-like standard synchronous Python. It uses `greenlet`_ to enable task10-switching without writing ``async/await`` or using ``asyncio``.11-12-:doc:`gevent` is another library that does the same thing. Certain13-dependencies you have, or other considerations, may affect which of the14-two you choose to use.15-16-eventlet provides a WSGI server that can handle many connections at once17-instead of one per worker process. You must actually use eventlet in18-your own code to see any benefit to using the server.19-20-.. _eventlet: https://eventlet.net/21-.. _greenlet: https://greenlet.readthedocs.io/en/latest/22-23-24-Installing25-----------26-27-When using eventlet, greenlet>=1.0 is required, otherwise context locals28-such as ``request`` will not work as expected. When using PyPy,29-PyPy>=7.3.7 is required.30-31-Create a virtualenv, install your application, then install32-``eventlet``.33-34-.. code-block:: text35-36- $ cd hello-app37- $ python -m venv .venv38- $ . .venv/bin/activate39- $ pip install . # install your application40- $ pip install eventlet41-42-43-Running44--------45-46-To use eventlet to serve your application, write a script that imports47-its ``wsgi.server``, as well as your app or app factory.48-49-.. code-block:: python50- :caption: ``wsgi.py``51-52- import eventlet53- from eventlet import wsgi54- from hello import create_app55-56- app = create_app()57- wsgi.server(eventlet.listen(("127.0.0.1", 8000)), app)58-59-.. code-block:: text60-61- $ python wsgi.py62- (x) wsgi starting up on http://127.0.0.1:800063-64-65-Binding Externally66-------------------67-68-eventlet should not be run as root because it would cause your69-application code to run as root, which is not secure. However, this70-means it will not be possible to bind to port 80 or 443. Instead, a71-reverse proxy such as :doc:`nginx` or :doc:`apache-httpd` should be used72-in front of eventlet.73-74-You 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.76-Don't do this when using a reverse proxy setup, otherwise it will be77-possible to bypass the proxy.78-79-``0.0.0.0`` is not a valid address to navigate to, you'd use a specific80-IP address in your browser.8+__ https://eventlet.readthedocs.iomodified:docs/deploying/gevent.rst+5 added-9 removed
5 unmodified lines6 configurable and production-tested servers.7 8 `gevent`_ allows writing asynchronous, coroutine-based code that looks9 like standard synchronous Python. It uses `greenlet`_ to enable task10-switching without writing ``async/await`` or using ``asyncio``.10+switching without writing ``async/await`` or using ``asyncio``. This is11+not the same as Python's ``async/await``, or the ASGI server spec.12 12-:doc:`eventlet` is another library that does the same thing. Certain13-dependencies you have, or other considerations, may affect which of the14-two you choose to use.15-13 gevent provides a WSGI server that can handle many connections at once17-instead of one per worker process. You must actually use gevent in your18-own code to see any benefit to using the server.14+instead of one per worker process. See :doc:`/gevent` for more15+information about enabling it in your application.16 17 .. _gevent: https://www.gevent.org/18 .. _greenlet: https://greenlet.readthedocs.io/en/latest/19 20 21 Installing22 ----------23 27-When using gevent, greenlet>=1.0 is required, otherwise context locals28-such as ``request`` will not work as expected. When using PyPy,24+When using gevent, greenlet>=1.0 is required. When using PyPy,25 PyPy>=7.3.7 is required.26 27 Create a virtualenv, install your application, then install ``gevent``.28 48 unmodified linesmodified:docs/deploying/gunicorn.rst+11 added-25 removed
6 unmodified lines7 * 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.12 13 This page outlines the basics of running Gunicorn. Be sure to read its14 `documentation`_ and use ``gunicorn --help`` to understand what features15 are available.76 unmodified lines92 ``0.0.0.0`` is not a valid address to navigate to, you'd use a specific93 IP address in your browser.94 95 96-Async with gevent or eventlet97------------------------------96+Async with gevent97+-----------------98 99-The default sync worker is appropriate for many use cases. If you need100-asynchronous support, Gunicorn provides workers using either `gevent`_101-or `eventlet`_. This is not the same as Python's ``async/await``, or the102-ASGI server spec. You must actually use gevent/eventlet in your own code103-to see any benefit to using the workers.99+The default sync worker is appropriate for most use cases. If you need numerous,100+long running, concurrent connections, Gunicorn provides an asynchronous worker101+using `gevent`_. This is not the same as Python's ``async/await``, or the ASGI102+server spec. See :doc:`/gevent` for more information about enabling it in your103+application.104 105-When using either gevent or eventlet, greenlet>=1.0 is required,106-otherwise context locals such as ``request`` will not work as expected.107-When using PyPy, PyPy>=7.3.7 is required.105+.. _gevent: https://www.gevent.org/106 109-To use gevent:107+When using gevent, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is108+required.109 110 .. code-block:: text111 112 $ 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: x118-119-To use eventlet:120-121-.. code-block:: text122-123- $ 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: x128-129-.. _gevent: https://www.gevent.org/130-.. _eventlet: https://eventlet.net/modified:docs/deploying/index.rst-1 removed
34 unmodified lines35 waitress36 mod_wsgi37 uwsgi38 gevent39- eventlet39 asgi40 41 WSGI servers have HTTP servers built-in. However, a dedicated HTTP42 server may be safer, more efficient, or more capable. Putting an HTTP36 unmodified linesmodified:docs/deploying/uwsgi.rst+9 added-11 removed
117 unmodified lines118 119 Async with gevent120 -----------------121 122-The default sync worker is appropriate for many use cases. If you need123-asynchronous support, uWSGI provides a `gevent`_ worker. This is not the124-same as Python's ``async/await``, or the ASGI server spec. You must125-actually use gevent in your own code to see any benefit to using the126-worker.122+The default sync worker is appropriate for most use cases. If you need numerous,123+long running, concurrent connections, uWSGI provides an asynchronous worker124+using `gevent`_. This is not the same as Python's ``async/await``, or the ASGI125+server spec. See :doc:`/gevent` for more information about enabling it in your126+application.127 128-When using gevent, greenlet>=1.0 is required, otherwise context locals129-such as ``request`` will not work as expected. When using PyPy,130-PyPy>=7.3.7 is required.128+.. _gevent: https://www.gevent.org/129 130+When using gevent, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is131+required.132+133 .. code-block:: text134 135 $ uwsgi --http 127.0.0.1:8000 --master --gevent 100 -w wsgi:app136 3 unmodified lines140 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] ***143-144-145-.. _gevent: https://www.gevent.org/modified:docs/async-await.rst+11 added-17 removed
21 unmodified lines22 method in views that inherit from the :class:`flask.views.View` class, as23 well as all the HTTP method handlers in views that inherit from the24 :class:`flask.views.MethodView` class.25 26-.. admonition:: Using ``async`` with greenlet26 28- 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.31-32-27 Performance28 -----------29 30 Async functions require an event loop to run. Flask, as a WSGI40 unmodified lines71 Flask based on the `ASGI`_ standard instead of WSGI. This allows it to72 handle many concurrent requests, long running requests, and websockets73 without requiring multiple worker processes or threads.74 81-It has also already been possible to run Flask with Gevent or Eventlet82-to get many of the benefits of async request handling. These libraries83-patch low-level Python functions to accomplish this, whereas ``async``/84-``await`` and ASGI use standard, modern Python capabilities. Deciding85-whether you should use Flask, Quart, or something else is ultimately up86-to understanding the specific needs of your project.75+It has also already been possible to :doc:`run Flask with Gevent </gevent>` to76+get many of the benefits of async request handling. Gevent patches low-level77+Python functions to accomplish this, whereas ``async``/``await`` and ASGI use78+standard, modern Python capabilities. Deciding whether you should use gevent79+with Flask, or Quart, or something else is ultimately up to understanding the80+specific needs of your project.81 88-.. _Quart: https://github.com/pallets/quart89-.. _ASGI: https://asgi.readthedocs.io/en/latest/82+.. _Quart: https://quart.palletsprojects.com83+.. _ASGI: https://asgi.readthedocs.io84 85 86 Extensions87 ----------25 unmodified lines113 114 Other event loops115 -----------------116 123-At the moment Flask only supports :mod:`asyncio`. It's possible to124-override :meth:`flask.Flask.ensure_sync` to change how async functions125-are wrapped to use a different library.117+At 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 use119+a different library. See :ref:`gevent-asyncio` for an example.added:docs/gevent.rst+125 added
1+Async with Gevent2+=================3+4+`Gevent`_ patches Python's standard library to run within special async workers5+called `greenlets`_. Gevent has existed since long before Python's native6+asyncio was available, and Flask has always worked with it.7+8+.. _gevent: https://www.gevent.org9+.. _greenlets: https://greenlet.readthedocs.io10+11+Gevent is a reliable way to handle numerous, long lived, concurrent connections,12+and to achieve similar capabilities to ASGI and asyncio. This works without13+needing to write ``async def`` or ``await`` anywhere, but relies on gevent and14+greenlet's low level manipulation of the Python interpreter.15+16+Deciding whether you should use gevent with Flask, or `Quart`_, or something17+else, is ultimately up to understanding the specific needs of your project.18+19+.. _quart: https://quart.palletsprojects.com20+21+22+Enabling gevent23+---------------24+25+You need to apply gevent's patching as early as possible in your code. This26+enables gevent's underlying event loop and converts many Python internals to run27+inside it. Add the following at the top of your project's module or top28+``__init__.py``:29+30+.. code-block:: python31+32+ import gevent.monkey33+ gevent.monkey.patch_all()34+35+When deploying in production, use :doc:`/deploying/gunicorn` or36+:doc:`/deploying/uwsgi` with a gevent worker, as described on those pages.37+38+To run concurrent tasks within your own code, such as views, use39+|gevent.spawn|_:40+41+.. |gevent.spawn| replace:: ``gevent.spawn()``42+.. _gevent.spawn: https://www.gevent.org/api/gevent.html#gevent.spawn43+44+.. code-block:: python45+46+ @app.post("/send")47+ def send_email():48+ gevent.spawn(email.send, to="example@example.example", text="example")49+ return "Email is being sent."50+51+If you need to access :data:`request` or other Flask context globals within the52+spawned function, decorate the function with :func:`.stream_with_context` or53+:func:`.copy_current_request_context`. Prefer passing the exact data you need54+when spawning the function, rather than using the decorators.55+56+.. note::57+58+ When using gevent, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.759+ is required.60+61+62+.. _gevent-asyncio:63+64+Combining with ``async``/``await``65+----------------------------------66+67+Gevent's patching does not interact well with Flask's built-in asyncio support.68+If 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.70+71+.. code-block:: python72+73+ import gevent.monkey74+ gevent.monkey.patch_all()75+76+ import asyncio77+ from flask import Flask, request78+79+ loop = asyncio.EventLoop()80+ gevent.spawn(loop.run_forever)81+82+ 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()88+89+ return run90+91+ app = GeventFlask(__name__)92+93+ @app.get("/")94+ async def greet():95+ await asyncio.sleep(1)96+ return f"Hello, {request.args.get("name", "World")}!"97+98+This starts an asyncio event loop in a gevent worker. Async functions are99+scheduled on that event loop. This may still have limitations, and may need to100+be modified further when using other asyncio implementations.101+102+103+libuv104+~~~~~105+106+`libuv`_ is another event loop implementation that `gevent supports`_. There's107+also a project called `uvloop`_ that enables libuv in asyncio. If you want to108+use libuv, use gevent's support, not uvloop. It may be possible to further109+modify the ``async_to_sync`` code from the previous section to work with uvloop,110+but that's not currently known.111+112+.. _libuv: https://libuv.org/113+.. _gevent supports: https://www.gevent.org/loop_impls.html114+.. _uvloop: https://uvloop.readthedocs.io/115+116+To enable gevent's libuv support, add the following at the *very* top of your117+code, before ``gevent.monkey.patch_all()``:118+119+.. code-block:: python120+121+ import gevent122+ gevent.config.loop = "libuv"123+124+ import gevent.monkey125+ gevent.monkey.patch_all()modified:docs/index.rst+1 added
59 unmodified lines60 shell61 patterns/index62 web-security63 deploying/index64+ gevent65 async-await66 67 68 API Reference22 unmodified linesmodified:docs/installation.rst+2 added-3 removed
49 unmodified lines50 51 greenlet52 ~~~~~~~~53 54-You may choose to use gevent or eventlet with your application. In this55-case, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is56-required.54+You may choose to use :doc:`/gevent` with your application. In this case,55+greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is required.56 57 These are not minimum supported versions, they only indicate the first58 versions that added necessary features. You should use the latest59 versions of each.84 unmodified lines