Skip to content
Myr

gevent.rst

This file

Path

docs/gevent.rst

125 lines · 4.0 KiB

Last changed by

Merge branch 'stable'David Lordbefore adoption798e006

History of this file

Take it

Merge branch 'stable'David Lordbefore adoption798e006

lines 1–125why, one step back
1Async with Gevent
2=================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()