Skip to content
Myr

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

4 files+34 added−3 removed

modified:docs/async-await.rst+6 added
16 unmodified lines
17 async def get_data():18 data = await async_db_query(...)19 return jsonify(data)2021Pluggable class-based views also support handlers that are implemented as22coroutines. This applies to the :meth:`~flask.views.View.dispatch_request`23method in views that inherit from the :class:`flask.views.View` class, as24well as all the HTTP method handlers in views that inherit from the25:class:`flask.views.MethodView` class.2627.. admonition:: Using ``async`` on Windows on Python 3.82829 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 lines
modified:src/flask/views.py+3 added-2 removed
1import typing as t23from .globals import current_app4from .globals import request5from .typing import ResponseReturnValue67
72 unmodified lines
80 """8182 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)8586 if cls.decorators:87 view.__name__ = name88 view.__module__ = cls.__module__
65 unmodified lines
154 if meth is None and request.method == "HEAD":155 meth = getattr(self, "get", None)156157 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 lines
56from flask import Blueprint7from flask import Flask8from flask import request9from flask.views import MethodView10from flask.views import View1112pytest.importorskip("asgiref")1314
4 unmodified lines
19class BlueprintError(Exception):20 pass212223class AsyncView(View):24 methods = ["GET", "POST"]2526 async def dispatch_request(self):27 await asyncio.sleep(0)28 return request.method293031class AsyncMethodView(MethodView):32 async def get(self):33 await asyncio.sleep(0)34 return 'GET'3536 async def post(self):37 await asyncio.sleep(0)38 return 'POST'394041@pytest.fixture(name="async_app")42def _async_app():43 app = Flask(__name__)44
27 unmodified lines
72 raise BlueprintError()7374 app.register_blueprint(blueprint, url_prefix="/bp")7576 app.add_url_rule('/view', view_func=AsyncView.as_view('view'))77 app.add_url_rule('/methodview', view_func=AsyncMethodView.as_view('methodview'))7879 return app808182@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"])84def 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 lines
modified:CHANGES.rst+1 added
8 unmodified lines
9- 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`141516Version 2.0.117-------------
1154 unmodified lines