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
Provenance
- Commit
dc3e9c0- Tree
8f5b159- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
61fbae8
7 files changed+109 added−65 removed
deleted:docs/async_await.rst-46 removed
1-.. _async_await:2-3-Using async and await4-=====================5-6-.. versionadded:: 2.07-8-Routes, error handlers, before request, after request, and teardown9-functions can all be coroutine functions if Flask is installed with10-the ``async`` extra (``pip install flask[async]``). This allows code11-such as,12-13-.. code-block:: python14-15- @app.route("/")16- async def index():17- return await ...18-19-including the usage of any asyncio based libraries.20-21-22-When to use Quart instead23--------------------------24-25-Flask's ``async/await`` support is less performant than async first26-frameworks due to the way it is implemented. Therefore if you have a27-mainly async codebase it would make sense to consider `Quart28-<https://gitlab.com/pgjones/quart>`_. Quart is a reimplementation of29-the Flask using ``async/await`` based on the ASGI standard (Flask is30-based on the WSGI standard).31-32-33-Decorators34-----------35-36-Decorators designed for Flask, such as those in Flask extensions are37-unlikely to work. This is because the decorator will not await the38-coroutine function nor will they themselves be awaitable.39-40-41-Other event loops42------------------43-44-At the moment Flask only supports asyncio - the45-:meth:`flask.Flask.ensure_sync` should be overridden to support46-alternative event loops.added:docs/async-await.rst+81 added
1+.. _async_await:2+3+Using ``async`` and ``await``4+=============================5+6+.. versionadded:: 2.07+8+Routes, error handlers, before request, after request, and teardown9+functions can all be coroutine functions if Flask is installed with the10+``async`` extra (``pip install flask[async]``). This allows views to be11+defined with ``async def`` and use ``await``.12+13+.. code-block:: python14+15+ @app.route("/get-data")16+ async def get_data():17+ data = await async_db_query(...)18+ return jsonify(data)19+20+21+Performance22+-----------23+24+Async functions require an event loop to run. Flask, as a WSGI25+application, uses one worker to handle one request/response cycle.26+When a request comes in to an async view, Flask will start an event loop27+in a thread, run the view function there, then return the result.28+29+Each request still ties up one worker, even for async views. The upside30+is that you can run async code within a view, for example to make31+multiple concurrent database queries, HTTP requests to an external API,32+etc. However, the number of requests your application can handle at one33+time will remain the same.34+35+**Async is not inherently faster than sync code.** Async is beneficial36+when performing concurrent IO-bound tasks, but will probably not improve37+CPU-bound tasks. Traditional Flask views will still be appropriate for38+most use cases, but Flask's async support enables writing and using39+code that wasn't possible natively before.40+41+42+When to use Quart instead43+-------------------------44+45+Flask's async support is less performant than async-first frameworks due46+to the way it is implemented. If you have a mainly async codebase it47+would make sense to consider `Quart`_. Quart is a reimplementation of48+Flask based on the `ASGI`_ standard instead of WSGI. This allows it to49+handle many concurrent requests, long running requests, and websockets50+without requiring individual worker processes or threads.51+52+It has also already been possible to run Flask with Gevent or Eventlet53+to get many of the benefits of async request handling. These libraries54+patch low-level Python functions to accomplish this, whereas ``async``/55+``await`` and ASGI use standard, modern Python capabilities. Deciding56+whether you should use Flask, Quart, or something else is ultimately up57+to understanding the specific needs of your project.58+59+.. _Quart: https://gitlab.com/pgjones/quart60+.. _ASGI: https://asgi.readthedocs.io/en/latest/61+62+63+Extensions64+----------65+66+Existing Flask extensions only expect views to be synchronous. If they67+provide decorators to add functionality to views, those will probably68+not work with async views because they will not await the function or be69+awaitable. Other functions they provide will not be awaitable either and70+will probably be blocking if called within an async view.71+72+Check the changelog of the extension you want to use to see if they've73+implemented async support, or make a feature request or PR to them.74+75+76+Other event loops77+-----------------78+79+At the moment Flask only supports :mod:`asyncio`. It's possible to80+override :meth:`flask.Flask.ensure_sync` to change how async functions81+are wrapped to use a different library.modified:docs/design.rst+15 added-8 removed
169 unmodified lines170 Also see the :doc:`/becomingbig` section of the documentation for some171 inspiration for larger applications based on Flask.172 173 174-Async-await and ASGI support174+Async/await and ASGI support175 ----------------------------176 177-Flask supports ``async`` coroutines for view functions, and certain178-others by executing the coroutine on a seperate thread instead of179-utilising an event loop on the main thread as an async first (ASGI)180-frameworks would. This is necessary for Flask to remain backwards181-compatibility with extensions and code built before ``async`` was182-introduced into Python. This compromise introduces a performance cost183-compared with the ASGI frameworks, due to the overhead of the threads.177+Flask supports ``async`` coroutines for view functions by executing the178+coroutine on a separate thread instead of using an event loop on the179+main thread as an async-first (ASGI) framework would. This is necessary180+for Flask to remain backwards compatible with extensions and code built181+before ``async`` was introduced into Python. This compromise introduces182+a performance cost compared with the ASGI frameworks, due to the183+overhead of the threads.184 185+Due to how tied to WSGI Flask's code is, it's not clear if it's possible186+to make the ``Flask`` class support ASGI and WSGI at the same time. Work187+is currently being done in Werkzeug to work with ASGI, which may188+eventually enable support in Flask as well.189 190+See :doc:`/async-await` for more discussion.191+192+193 What Flask is, What Flask is Not194 --------------------------------195 196 Flask will never have a database layer. It will not have a form library12 unmodified linesmodified:docs/index.rst+1 added-1 removed
57 unmodified lines58 shell59 patterns/index60 deploying/index61 becomingbig62- async_await62+ async-await63 64 65 API Reference66 -------------25 unmodified linesmodified:src/flask/app.py+5 added-4 removed
1518 unmodified lines1519 """1520 return False1521 1522 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.1526 1525- .. versionadded:: 2.01527+ Override this method to change how the app runs async views.1528 1527- 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 linesmodified:src/flask/blueprints.py+2 added-2 removed
473 unmodified lines474 def ensure_sync(self, f):475 """Ensure the function is synchronous.476 477 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.480 481 .. versionadded:: 2.0482 """483 return fmodified:src/flask/helpers.py+5 added-4 removed
740 unmodified lines741 raise RuntimeError(742 "Install Flask with the 'async' extra in order to use async views."743 )744 745+ # 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 )750 751 @wraps(func)752 def outer(*args, **kwargs):10 unmodified lines763 @wraps(func)764 async def inner(*a, **k):765 """This restores the context before awaiting the func.766 766- 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