Add async support

This allows for async functions to be passed to the Flask class
instance, for example as a view function,

    @app.route("/")
    async def index():
        return "Async hello"

this comes with a cost though of poorer performance than using the
sync equivalent.

asgiref is the standard way to run async code within a sync context,
and is used in Django making it a safe and sane choice for this.
This commit is contained in:
pgjones 2020-07-06 20:54:26 +01:00 committed by David Lord
parent 85b8fab268
commit 6979265fa6
No known key found for this signature in database
GPG key ID: 7A1C87E3F5BC42A8
11 changed files with 165 additions and 9 deletions

46
docs/async_await.rst Normal file
View file

@ -0,0 +1,46 @@
.. _async_await:
Using async and await
=====================
.. versionadded:: 2.0
Routes, error handlers, before request, after request, and teardown
functions can all be coroutine functions if Flask is installed with
the ``async`` extra (``pip install flask[async]``). This allows code
such as,
.. code-block:: python
@app.route("/")
async def index():
return await ...
including the usage of any asyncio based libraries.
When to use Quart instead
-------------------------
Flask's ``async/await`` support is less performant than async first
frameworks due to the way it is implemented. Therefore if you have a
mainly async codebase it would make sense to consider `Quart
<https://gitlab.com/pgjones/quart>`_. Quart is a reimplementation of
the Flask using ``async/await`` based on the ASGI standard (Flask is
based on the WSGI standard).
Decorators
----------
Decorators designed for Flask, such as those in Flask extensions are
unlikely to work. This is because the decorator will not await the
coroutine function nor will they themselves be awaitable.
Other event loops
-----------------
At the moment Flask only supports asyncio - the
:meth:`flask.Flask.ensure_sync` should be overridden to support
alternative event loops.

View file

@ -171,6 +171,18 @@ Also see the :doc:`/becomingbig` section of the documentation for some
inspiration for larger applications based on Flask.
Async-await and ASGI support
----------------------------
Flask supports ``async`` coroutines for view functions, and certain
others by executing the coroutine on a seperate thread instead of
utilising an event loop on the main thread as an async first (ASGI)
frameworks would. This is necessary for Flask to remain backwards
compatibility with extensions and code built before ``async`` was
introduced into Python. This compromise introduces a performance cost
compared with the ASGI frameworks, due to the overhead of the threads.
What Flask is, What Flask is Not
--------------------------------

View file

@ -59,6 +59,7 @@ instructions for web development with Flask.
patterns/index
deploying/index
becomingbig
async_await
API Reference