Skip to content
Myr

async-await.rst

This file

Path

docs/async-await.rst

119 lines · 4.6 KiB

Last changed by

Merge branch 'stable'David Lordbefore adoption798e006

History of this file

Take it

1.. _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.252627Performance28-----------2930Async functions require an event loop to run. Flask, as a WSGI31application, uses one worker to handle one request/response cycle.32When a request comes in to an async view, Flask will start an event loop33in a thread, run the view function there, then return the result.3435Each request still ties up one worker, even for async views. The upside36is that you can run async code within a view, for example to make37multiple concurrent database queries, HTTP requests to an external API,38etc. However, the number of requests your application can handle at one39time will remain the same.4041**Async is not inherently faster than sync code.** Async is beneficial42when performing concurrent IO-bound tasks, but will probably not improve43CPU-bound tasks. Traditional Flask views will still be appropriate for44most use cases, but Flask's async support enables writing and using45code that wasn't possible natively before.464748Background tasks49----------------5051Async functions will run in an event loop until they complete, at52which stage the event loop will stop. This means any additional53spawned tasks that haven't completed when the async function completes54will be cancelled. Therefore you cannot spawn background tasks, for55example via ``asyncio.create_task``.5657If you wish to use background tasks it is best to use a task queue to58trigger background work, rather than spawn tasks in a view59function. With that in mind you can spawn asyncio tasks by serving60Flask with an ASGI server and utilising the asgiref WsgiToAsgi adapter61as described in :doc:`deploying/asgi`. This works as the adapter creates62an event loop that runs continually.636465When to use Quart instead66-------------------------6768Flask's async support is less performant than async-first frameworks due69to the way it is implemented. If you have a mainly async codebase it70would make sense to consider `Quart`_. Quart is a reimplementation of71Flask 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.7475It 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.8182.. _Quart: https://quart.palletsprojects.com83.. _ASGI: https://asgi.readthedocs.io848586Extensions87----------8889Flask extensions predating Flask's async support do not expect async views.90If they provide decorators to add functionality to views, those will probably91not work with async views because they will not await the function or be92awaitable. Other functions they provide will not be awaitable either and93will probably be blocking if called within an async view.9495Extension authors can support async functions by utilising the96:meth:`flask.Flask.ensure_sync` method. For example, if the extension97provides a view function decorator add ``ensure_sync`` before calling98the decorated function,99100.. code-block:: python101102    def extension(func):103        @wraps(func)104        def wrapper(*args, **kwargs):105            ...  # Extension logic106            return current_app.ensure_sync(func)(*args, **kwargs)107108        return wrapper109110Check the changelog of the extension you want to use to see if they've111implemented async support, or make a feature request or PR to them.112113114Other event loops115-----------------116117At 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.