Skip to content
Myr

Add `async` support

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

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.

authored by pgjones · committed by David Lord · parent 85b8fab · Browse files · 11 files+165 added−9 removed
This commit

State

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

Diff stats

11 files+165 added−9 removed

  • tests:+33 added−0 removed
  • other:+132 added−9 removed

11 files+165 added−9 removed

added:docs/async_await.rst+46 added
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.
modified:docs/design.rst+12 added
169 unmodified lines
170Also see the :doc:`/becomingbig` section of the documentation for some171inspiration for larger applications based on Flask.172173174Async-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.184185186What Flask is, What Flask is Not187--------------------------------188189Flask will never have a database layer. It will not have a form library
12 unmodified lines
modified:docs/index.rst+1 added
57 unmodified lines
58 shell59 patterns/index60 deploying/index61 becomingbig62 async_await636465API Reference66-------------
25 unmodified lines
modified:requirements/tests.in+1 added
1pytest2asgiref3blinker4greenlet5python-dotenv
modified:requirements/tests.txt+2 added
2 unmodified lines
3# To update, run:4#5# pip-compile requirements/tests.in6#7asgiref==3.2.108 # via -r requirements/tests.in9attrs==20.3.010 # via pytest11blinker==1.412 # via -r requirements/tests.in
18 unmodified lines
modified:src/flask/app.py+3 added-3 removed
1048 unmodified lines
1049 raise AssertionError(1050 "View function mapping is overwriting an existing"1051 f" endpoint function: {endpoint}"1052 )1053 self.view_functions[endpoint] = view_func1053 self.view_functions[endpoint] = self.ensure_sync(view_func)10541055 @setupmethod1056 def template_filter(self, name=None):1057 """A decorator that is used to register custom template filter.
106 unmodified lines
1164 value is ignored.11651166 .. versionadded:: 0.81167 """1168 self.before_first_request_funcs.append(f)1168 self.before_first_request_funcs.append(self.ensure_sync(f))1169 return f11701171 @setupmethod1172 def teardown_appcontext(self, f):
24 unmodified lines
1197 The return values of teardown functions are ignored.11981199 .. versionadded:: 0.91200 """1201 self.teardown_appcontext_funcs.append(f)1201 self.teardown_appcontext_funcs.append(self.ensure_sync(f))1202 return f12031204 @setupmethod1205 def shell_context_processor(self, f):
751 unmodified lines
modified:src/flask/helpers.py+41 added
1import os2import socket3import warnings4from functools import update_wrapper5from functools import wraps6from threading import RLock78import werkzeug.utils9from werkzeug.exceptions import NotFound
719 unmodified lines
729 else:730 return True731732 return False733734735def run_async(func):736 """Return a sync function that will run the coroutine function *func*."""737 try:738 from asgiref.sync import async_to_sync739 except ImportError:740 raise RuntimeError(741 "Install Flask with the 'async' extra in order to use async views."742 )743744 @wraps(func)745 def outer(*args, **kwargs):746 """This function grabs the current context for the inner function.747748 This is similar to the copy_current_xxx_context functions in the749 ctx module, except it has an async inner.750 """751 ctx = None752 if _request_ctx_stack.top is not None:753 ctx = _request_ctx_stack.top.copy()754755 @wraps(func)756 async def inner(*a, **k):757 """This restores the context before awaiting the func.758759 This is required as the func must be awaited within the760 context. Simply calling func (as per the761 copy_current_xxx_context functions) doesn't work as the762 with block will close before the coroutine is awaited.763 """764 if ctx is not None:765 with ctx:766 return await func(*a, **k)767 else:768 return await func(*a, **k)769770 return async_to_sync(inner)(*args, **kwargs)771772 return outer
modified:src/flask/scaffold.py+20 added-5 removed
2 unmodified lines
3import pkgutil4import sys5from collections import defaultdict6from functools import update_wrapper7from inspect import iscoroutinefunction89from jinja2 import FileSystemLoader10from werkzeug.exceptions import default_exceptions11from werkzeug.exceptions import HTTPException1213from .cli import AppGroup14from .globals import current_app15from .helpers import locked_cached_property16from .helpers import run_async17from .helpers import send_from_directory18from .templating import _default_template_ctx_processor1920# a singleton sentinel value for parameter defaults
464 unmodified lines
485 function.486 """487488 def decorator(f):487 self.view_functions[endpoint] = f489 self.view_functions[endpoint] = self.ensure_sync(f)490 return f491492 return decorator493
15 unmodified lines
509 a non-``None`` value, the value is handled as if it was the510 return value from the view, and further request handling is511 stopped.512 """511 self.before_request_funcs[None].append(f)513 self.before_request_funcs.setdefault(None, []).append(self.ensure_sync(f))514 return f515516 @setupmethod517 def after_request(self, f):
7 unmodified lines
525 ``after_request`` functions will not be called. Therefore, this526 should not be used for actions that must execute, such as to527 close resources. Use :meth:`teardown_request` for that.528 """527 self.after_request_funcs[None].append(f)529 self.after_request_funcs.setdefault(None, []).append(self.ensure_sync(f))530 return f531532 @setupmethod533 def teardown_request(self, f):
30 unmodified lines
564 immediately. Instead it will keep it alive so that the interactive565 debugger can still access it. This behavior can be controlled566 by the ``PRESERVE_CONTEXT_ON_EXCEPTION`` configuration variable.567 """566 self.teardown_request_funcs[None].append(f)568 self.teardown_request_funcs.setdefault(None, []).append(self.ensure_sync(f))569 return f570571 @setupmethod572 def context_processor(self, f):
87 unmodified lines
660 " code. Use a subclass of HTTPException with that code"661 " instead."662 )663662 self.error_handler_spec[None][code][exc_class] = f664 self.error_handler_spec[None][code][exc_class] = self.ensure_sync(f)665666 @staticmethod667 def _get_exc_class_and_code(exc_class_or_code):668 """Get the exception class being handled. For HTTP status codes
16 unmodified lines
685 return exc_class, exc_class.code686 else:687 return exc_class, None688689 def ensure_sync(self, func):690 """Ensure that the returned function is sync and calls the async func.691692 .. versionadded:: 2.0693694 Override if you wish to change how asynchronous functions are695 run.696 """697 if iscoroutinefunction(func):698 return run_async(func)699 else:700 return func701702703def _endpoint_from_view_func(view_func):704 """Internal helper that returns the default endpoint for a given705 function. This always is the function name.706 """
170 unmodified lines
added:tests/test_async.py+33 added
1import asyncio23import pytest45from flask import abort6from flask import Flask7from flask import request8910@pytest.fixture(name="async_app")11def _async_app():12 app = Flask(__name__)1314 @app.route("/", methods=["GET", "POST"])15 async def index():16 await asyncio.sleep(0)17 return request.method1819 @app.route("/error")20 async def error():21 abort(412)2223 return app242526def test_async_request_context(async_app):27 test_client = async_app.test_client()28 response = test_client.get("/")29 assert b"GET" in response.get_data()30 response = test_client.post("/")31 assert b"POST" in response.get_data()32 response = test_client.get("/error")33 assert response.status_code == 412
modified:CHANGES.rst+2 added
65 unmodified lines
66- Use Jinja's implementation of the ``|tojson`` filter. :issue:`3881`67- Add route decorators for common HTTP methods. For example,68 ``@app.post("/login")`` is a shortcut for69 ``@app.route("/login", methods=["POST"])``. :pr:`3907`70- Support async views, error handlers, before and after request, and71 teardown functions. :pr:`3412`727374Version 1.1.275-------------
1011 unmodified lines
modified:setup.py+4 added-1 removed
7 unmodified lines
8 "Jinja2>=2.10.1",9 "itsdangerous>=0.24",10 "click>=5.1",11 ],12 extras_require={"dotenv": ["python-dotenv"]},12 extras_require={13 "async": ["asgiref>=3.2"],14 "dotenv": ["python-dotenv"],15 },16)