async-await.rst
This file
Path
docs/async-await.rst
131 lines · 5.0 KiB
Last changed by
Merge branch '2.1.x'David Lordbefore adoption48fe965
History of this fileTake it
The walk stopped after 200 commits: lines older than 93a7f08 point at it.
pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 1–72why, one step back1.. _async_await:23Using ``async`` and ``await``4=============================56.. versionadded:: 2.078Routes, error handlers, before request, after request, and teardown9functions can all be coroutine functions if Flask is installed with the10``async`` extra (``pip install flask[async]``). This allows views to be11defined with ``async def`` and use ``await``.1213.. code-block:: python1415 @app.route("/get-data")16 async def get_data():17 data = await async_db_query(...)18 return jsonify(data)1920Pluggable class-based views also support handlers that are implemented as21coroutines. This applies to the :meth:`~flask.views.View.dispatch_request`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`` on Windows on Python 3.82728 Python 3.8 has a bug related to asyncio on Windows. If you encounter29 something like ``ValueError: set_wakeup_fd only works in main thread``,30 please upgrade to Python 3.9.3132.. admonition:: Using ``async`` with greenlet3334 When using gevent or eventlet to serve an application or patch the35 runtime, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is36 required.373839Performance40-----------4142Async functions require an event loop to run. Flask, as a WSGI43application, uses one worker to handle one request/response cycle.44When a request comes in to an async view, Flask will start an event loop45in a thread, run the view function there, then return the result.4647Each request still ties up one worker, even for async views. The upside48is that you can run async code within a view, for example to make49multiple concurrent database queries, HTTP requests to an external API,50etc. However, the number of requests your application can handle at one51time will remain the same.5253**Async is not inherently faster than sync code.** Async is beneficial54when performing concurrent IO-bound tasks, but will probably not improve55CPU-bound tasks. Traditional Flask views will still be appropriate for56most use cases, but Flask's async support enables writing and using57code that wasn't possible natively before.585960Background tasks61----------------6263Async functions will run in an event loop until they complete, at64which stage the event loop will stop. This means any additional65spawned tasks that haven't completed when the async function completes66will be cancelled. Therefore you cannot spawn background tasks, for67example via ``asyncio.create_task``.6869If you wish to use background tasks it is best to use a task queue to70trigger background work, rather than spawn tasks in a view71function. With that in mind you can spawn asyncio tasks by serving72Flask with an ASGI server and utilising the asgiref WsgiToAsgi adapterMerge branch '2.1.x'David Lordbefore adoption9139af1
lines 73–74why, one step back73as described in :doc:`deploying/asgi`. This works as the adapter creates74an event loop that runs continually.pin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 75–93why, one step back757677When to use Quart instead78-------------------------7980Flask's async support is less performant than async-first frameworks due81to the way it is implemented. If you have a mainly async codebase it82would make sense to consider `Quart`_. Quart is a reimplementation of83Flask based on the `ASGI`_ standard instead of WSGI. This allows it to84handle many concurrent requests, long running requests, and websockets85without requiring multiple worker processes or threads.8687It has also already been possible to run Flask with Gevent or Eventlet88to get many of the benefits of async request handling. These libraries89patch low-level Python functions to accomplish this, whereas ``async``/90``await`` and ASGI use standard, modern Python capabilities. Deciding91whether you should use Flask, Quart, or something else is ultimately up92to understanding the specific needs of your project.93Merge branch '2.1.x'David Lordbefore adoption48fe965
line 94why, one step back94.. _Quart: https://github.com/pallets/quartpin os and python version in rtd buildDavid Lordbefore adoption93a7f08
lines 95–131why, one step back95.. _ASGI: https://asgi.readthedocs.io/en/latest/969798Extensions99----------100101Flask extensions predating Flask's async support do not expect async views.102If they provide decorators to add functionality to views, those will probably103not work with async views because they will not await the function or be104awaitable. Other functions they provide will not be awaitable either and105will probably be blocking if called within an async view.106107Extension authors can support async functions by utilising the108:meth:`flask.Flask.ensure_sync` method. For example, if the extension109provides a view function decorator add ``ensure_sync`` before calling110the decorated function,111112.. code-block:: python113114 def extension(func):115 @wraps(func)116 def wrapper(*args, **kwargs):117 ... # Extension logic118 return current_app.ensure_sync(func)(*args, **kwargs)119120 return wrapper121122Check the changelog of the extension you want to use to see if they've123implemented async support, or make a feature request or PR to them.124125126Other event loops127-----------------128129At the moment Flask only supports :mod:`asyncio`. It's possible to130override :meth:`flask.Flask.ensure_sync` to change how async functions131are wrapped to use a different library.