|
| 1 | +Async with Gevent |
| 2 | +================= |
| 3 | + |
| 4 | +`Gevent`_ patches Python's standard library to run within special async workers |
| 5 | +called `greenlets`_. Gevent has existed since long before Python's native |
| 6 | +asyncio was available, and Flask has always worked with it. |
| 7 | + |
| 8 | +.. _gevent: https://www.gevent.org |
| 9 | +.. _greenlets: https://greenlet.readthedocs.io |
| 10 | + |
| 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 without |
| 13 | +needing to write ``async def`` or ``await`` anywhere, but relies on gevent and |
| 14 | +greenlet's low level manipulation of the Python interpreter. |
| 15 | + |
| 16 | +Deciding whether you should use gevent with Flask, or `Quart`_, or something |
| 17 | +else, is ultimately up to understanding the specific needs of your project. |
| 18 | + |
| 19 | +.. _quart: https://quart.palletsprojects.com |
| 20 | + |
| 21 | + |
| 22 | +Enabling gevent |
| 23 | +--------------- |
| 24 | + |
| 25 | +You need to apply gevent's patching as early as possible in your code. This |
| 26 | +enables gevent's underlying event loop and converts many Python internals to run |
| 27 | +inside it. Add the following at the top of your project's module or top |
| 28 | +``__init__.py``: |
| 29 | + |
| 30 | +.. code-block:: python |
| 31 | +
|
| 32 | + import gevent.monkey |
| 33 | + gevent.monkey.patch_all() |
| 34 | +
|
| 35 | +When deploying in production, use :doc:`/deploying/gunicorn` or |
| 36 | +: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, use |
| 39 | +|gevent.spawn|_: |
| 40 | + |
| 41 | +.. |gevent.spawn| replace:: ``gevent.spawn()`` |
| 42 | +.. _gevent.spawn: https://www.gevent.org/api/gevent.html#gevent.spawn |
| 43 | + |
| 44 | +.. code-block:: python |
| 45 | +
|
| 46 | + @app.post("/send") |
| 47 | + def send_email(): |
| 48 | + gevent.spawn(email.send, to="[email protected]", text="example") |
| 49 | + return "Email is being sent." |
| 50 | +
|
| 51 | +If you need to access :data:`request` or other Flask context globals within the |
| 52 | +spawned function, decorate the function with :func:`.stream_with_context` or |
| 53 | +:func:`.copy_current_request_context`. Prefer passing the exact data you need |
| 54 | +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.7 |
| 59 | + 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 override |
| 69 | +:meth:`flask.Flask.async_to_sync` to run async functions inside gevent. |
| 70 | + |
| 71 | +.. code-block:: python |
| 72 | +
|
| 73 | + import gevent.monkey |
| 74 | + gevent.monkey.patch_all() |
| 75 | +
|
| 76 | + import asyncio |
| 77 | + from flask import Flask, request |
| 78 | +
|
| 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 run |
| 90 | +
|
| 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 are |
| 99 | +scheduled on that event loop. This may still have limitations, and may need to |
| 100 | +be modified further when using other asyncio implementations. |
| 101 | + |
| 102 | + |
| 103 | +libuv |
| 104 | +~~~~~ |
| 105 | + |
| 106 | +`libuv`_ is another event loop implementation that `gevent supports`_. There's |
| 107 | +also a project called `uvloop`_ that enables libuv in asyncio. If you want to |
| 108 | +use libuv, use gevent's support, not uvloop. It may be possible to further |
| 109 | +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.html |
| 114 | +.. _uvloop: https://uvloop.readthedocs.io/ |
| 115 | + |
| 116 | +To enable gevent's libuv support, add the following at the *very* top of your |
| 117 | +code, before ``gevent.monkey.patch_all()``: |
| 118 | + |
| 119 | +.. code-block:: python |
| 120 | +
|
| 121 | + import gevent |
| 122 | + gevent.config.loop = "libuv" |
| 123 | +
|
| 124 | + import gevent.monkey |
| 125 | + gevent.monkey.patch_all() |
0 commit comments