Skip to content
Myr

update async docs

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent 61fbae8 · Browse files · 7 files+109 added−65 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

7 files+109 added−65 removed

  • other:+109 added−65 removed

7 files+109 added−65 removed

deleted:docs/async_await.rst-46 removed
1.. _async_await:23Using async and await4=====================56.. versionadded:: 2.078Routes, error handlers, before request, after request, and teardown9functions can all be coroutine functions if Flask is installed with10the ``async`` extra (``pip install flask[async]``). This allows code11such as,1213.. code-block:: python1415 @app.route("/")16 async def index():17 return await ...1819including the usage of any asyncio based libraries.202122When to use Quart instead23-------------------------2425Flask's ``async/await`` support is less performant than async first26frameworks due to the way it is implemented. Therefore if you have a27mainly async codebase it would make sense to consider `Quart28<https://gitlab.com/pgjones/quart>`_. Quart is a reimplementation of29the Flask using ``async/await`` based on the ASGI standard (Flask is30based on the WSGI standard).313233Decorators34----------3536Decorators designed for Flask, such as those in Flask extensions are37unlikely to work. This is because the decorator will not await the38coroutine function nor will they themselves be awaitable.394041Other event loops42-----------------4344At the moment Flask only supports asyncio - the45:meth:`flask.Flask.ensure_sync` should be overridden to support46alternative event loops.
added:docs/async-await.rst+81 added
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)192021Performance22-----------2324Async functions require an event loop to run. Flask, as a WSGI25application, uses one worker to handle one request/response cycle.26When a request comes in to an async view, Flask will start an event loop27in a thread, run the view function there, then return the result.2829Each request still ties up one worker, even for async views. The upside30is that you can run async code within a view, for example to make31multiple concurrent database queries, HTTP requests to an external API,32etc. However, the number of requests your application can handle at one33time will remain the same.3435**Async is not inherently faster than sync code.** Async is beneficial36when performing concurrent IO-bound tasks, but will probably not improve37CPU-bound tasks. Traditional Flask views will still be appropriate for38most use cases, but Flask's async support enables writing and using39code that wasn't possible natively before.404142When to use Quart instead43-------------------------4445Flask's async support is less performant than async-first frameworks due46to the way it is implemented. If you have a mainly async codebase it47would make sense to consider `Quart`_. Quart is a reimplementation of48Flask based on the `ASGI`_ standard instead of WSGI. This allows it to49handle many concurrent requests, long running requests, and websockets50without requiring individual worker processes or threads.5152It has also already been possible to run Flask with Gevent or Eventlet53to get many of the benefits of async request handling. These libraries54patch low-level Python functions to accomplish this, whereas ``async``/55``await`` and ASGI use standard, modern Python capabilities. Deciding56whether you should use Flask, Quart, or something else is ultimately up57to understanding the specific needs of your project.5859.. _Quart: https://gitlab.com/pgjones/quart60.. _ASGI: https://asgi.readthedocs.io/en/latest/616263Extensions64----------6566Existing Flask extensions only expect views to be synchronous. If they67provide decorators to add functionality to views, those will probably68not work with async views because they will not await the function or be69awaitable. Other functions they provide will not be awaitable either and70will probably be blocking if called within an async view.7172Check the changelog of the extension you want to use to see if they've73implemented async support, or make a feature request or PR to them.747576Other event loops77-----------------7879At the moment Flask only supports :mod:`asyncio`. It's possible to80override :meth:`flask.Flask.ensure_sync` to change how async functions81are wrapped to use a different library.
modified:docs/design.rst+15 added-8 removed
169 unmodified lines
170Also see the :doc:`/becomingbig` section of the documentation for some171inspiration for larger applications based on Flask.172173174Async-await and ASGI support174Async/await and ASGI support175----------------------------176177Flask supports ``async`` coroutines for view functions, and certain178others by executing the coroutine on a seperate thread instead of179utilising an event loop on the main thread as an async first (ASGI)180frameworks would. This is necessary for Flask to remain backwards181compatibility with extensions and code built before ``async`` was182introduced into Python. This compromise introduces a performance cost183compared with the ASGI frameworks, due to the overhead of the threads.177Flask supports ``async`` coroutines for view functions by executing the178coroutine on a separate thread instead of using an event loop on the179main thread as an async-first (ASGI) framework would. This is necessary180for Flask to remain backwards compatible with extensions and code built181before ``async`` was introduced into Python. This compromise introduces182a performance cost compared with the ASGI frameworks, due to the183overhead of the threads.184185Due to how tied to WSGI Flask's code is, it's not clear if it's possible186to make the ``Flask`` class support ASGI and WSGI at the same time. Work187is currently being done in Werkzeug to work with ASGI, which may188eventually enable support in Flask as well.189190See :doc:`/async-await` for more discussion.191192193What Flask is, What Flask is Not194--------------------------------195196Flask will never have a database layer. It will not have a form library
12 unmodified lines
modified:docs/index.rst+1 added-1 removed
57 unmodified lines
58 shell59 patterns/index60 deploying/index61 becomingbig62 async_await62 async-await636465API Reference66-------------
25 unmodified lines
modified:src/flask/app.py+5 added-4 removed
1518 unmodified lines
1519 """1520 return False15211522 def ensure_sync(self, func):1523 """Ensure that the returned function is sync and calls the async func.1523 """Ensure that the function is synchronous for WSGI workers.1524 Plain ``def`` functions are returned as-is. ``async def``1525 functions are wrapped to run and wait for the response.15261525 .. versionadded:: 2.01527 Override this method to change how the app runs async views.15281527 Override if you wish to change how asynchronous functions are1528 run.1529 .. versionadded:: 2.01530 """1531 if iscoroutinefunction(func):1532 return run_async(func)1533
439 unmodified lines
modified:src/flask/blueprints.py+2 added-2 removed
473 unmodified lines
474 def ensure_sync(self, f):475 """Ensure the function is synchronous.476477 Override if you would like custom async to sync behaviour in478 this blueprint. Otherwise :meth:`~flask.Flask..ensure_sync` is479 used.478 this blueprint. Otherwise the app's479 :meth:`~flask.Flask.ensure_sync` is used.480481 .. versionadded:: 2.0482 """483 return f
modified:src/flask/helpers.py+5 added-4 removed
740 unmodified lines
741 raise RuntimeError(742 "Install Flask with the 'async' extra in order to use async views."743 )744745 # Check that Werkzeug isn't using its fallback ContextVar class.746 if ContextVar.__module__ == "werkzeug.local":747 raise RuntimeError(747 "async cannot be used with this combination of Python & Greenlet versions"748 "Async cannot be used with this combination of Python & Greenlet versions."749 )750751 @wraps(func)752 def outer(*args, **kwargs):
10 unmodified lines
763 @wraps(func)764 async def inner(*a, **k):765 """This restores the context before awaiting the func.766766 This is required as the func must be awaited within the767 context. Simply calling func (as per the768 copy_current_xxx_context functions) doesn't work as the767 This is required as the function must be awaited within the768 context. Only calling ``func`` (as per the769 ``copy_current_xxx_context`` functions) doesn't work as the770 with block will close before the coroutine is awaited.771 """772 if ctx is not None:773 with ctx:
7 unmodified lines