Support View and MethodView instances with async handlers
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Miguel Grinberg · committed by Phil Jones · parent 491ea32 · Browse files · 4 files·+34 added−3 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+34 added−3 removed
- tests:+24 added−1 removed
- other:+10 added−2 removed
Provenance
- Commit
270eb2d- Tree
2dddc6f- Author
Miguel Grinberg <miguel.grinberg@gmail.com>- Committer
Phil Jones <philip.graham.jones@googlemail.com>- Parent
491ea32
4 files changed+34 added−3 removed
modified:docs/async-await.rst+6 added
16 unmodified lines17 async def get_data():18 data = await async_db_query(...)19 return jsonify(data)20 21+Pluggable class-based views also support handlers that are implemented as22+coroutines. This applies to the :meth:`~flask.views.View.dispatch_request`23+method in views that inherit from the :class:`flask.views.View` class, as24+well as all the HTTP method handlers in views that inherit from the25+:class:`flask.views.MethodView` class.26+27 .. admonition:: Using ``async`` on Windows on Python 3.828 29 Python 3.8 has a bug related to asyncio on Windows. If you encounter30 something like ``ValueError: set_wakeup_fd only works in main thread``,96 unmodified linesmodified:src/flask/views.py+3 added-2 removed
1 import typing as t2 3+from .globals import current_app4 from .globals import request5 from .typing import ResponseReturnValue6 7 72 unmodified lines80 """81 82 def view(*args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:83 self = view.view_class(*class_args, **class_kwargs) # type: ignore83- return self.dispatch_request(*args, **kwargs)84+ return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)85 86 if cls.decorators:87 view.__name__ = name88 view.__module__ = cls.__module__65 unmodified lines154 if meth is None and request.method == "HEAD":155 meth = getattr(self, "get", None)156 157 assert meth is not None, f"Unimplemented method {request.method!r}"157- return meth(*args, **kwargs)158+ return current_app.ensure_sync(meth)(*args, **kwargs)modified:tests/test_async.py+24 added-1 removed
4 unmodified lines5 6 from flask import Blueprint7 from flask import Flask8 from flask import request9+from flask.views import MethodView10+from flask.views import View11 12 pytest.importorskip("asgiref")13 14 4 unmodified lines19 class BlueprintError(Exception):20 pass21 22 23+class AsyncView(View):24+ methods = ["GET", "POST"]25+26+ async def dispatch_request(self):27+ await asyncio.sleep(0)28+ return request.method29+30+31+class AsyncMethodView(MethodView):32+ async def get(self):33+ await asyncio.sleep(0)34+ return 'GET'35+36+ async def post(self):37+ await asyncio.sleep(0)38+ return 'POST'39+40+41 @pytest.fixture(name="async_app")42 def _async_app():43 app = Flask(__name__)44 27 unmodified lines72 raise BlueprintError()73 74 app.register_blueprint(blueprint, url_prefix="/bp")75 76+ app.add_url_rule('/view', view_func=AsyncView.as_view('view'))77+ app.add_url_rule('/methodview', view_func=AsyncMethodView.as_view('methodview'))78+79 return app80 81 82 @pytest.mark.skipif(sys.version_info < (3, 7), reason="requires Python >= 3.7")60-@pytest.mark.parametrize("path", ["/", "/home", "/bp/"])83+@pytest.mark.parametrize("path", ["/", "/home", "/bp/", "/view", "/methodview"])84 def test_async_route(path, async_app):85 test_client = async_app.test_client()86 response = test_client.get(path)87 assert b"GET" in response.get_data()76 unmodified linesmodified:CHANGES.rst+1 added
8 unmodified lines9 - Fix type annotation for ``before_request`` and ``before_app_request``10 decorators. :issue:`4104`11 - Fixed the issue where typing requires template global12 decorators to accept functions with no arguments. :issue:`4098`13+- Support View and MethodView instances with async handlers. :issue:`4112`14 15 16 Version 2.0.117 -------------1154 unmodified lines