Merge remote-tracking branch 'origin/2.0.x' into main
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Grey Li · committed by Grey Li · parents aac6728, 49cbb77 · Browse files · 15 files·+118 added−43 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+118 added−43 removed
- tests:+34 added−1 removed
- other:+84 added−42 removed
Provenance
- Commit
ba6db2e- Tree
767d363- Author
Grey Li <withlihui@gmail.com>- Committer
Grey Li <withlihui@gmail.com>- Parent 1
aac6728- Parent 2
49cbb77
15 files changed+118 added−43 removed
modified:docs/patterns/celery.rst+1 added-1 removed
62 unmodified lines63 ---------------64 65 Let's write a task that adds two numbers together and returns the result. We66 configure Celery's broker and backend to use Redis, create a ``celery``67-application using the factor from above, and then use it to define the task. ::67+application using the factory from above, and then use it to define the task. ::68 69 from flask import Flask70 71 flask_app = Flask(__name__)30 unmodified linesmodified:docs/async-await.rst+8 added-1 removed
5 unmodified lines6 .. 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 be10+``async`` extra (``pip install flask[async]``). It requires Python 3.7+11+where ``contextvars.ContextVar`` is available. This allows views to be12 defined with ``async def`` and use ``await``.13 14 .. code-block:: python15 1 unmodified line17 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:docs/installation.rst+2 added
6 unmodified lines7 8 We recommend using the latest version of Python. Flask supports Python9 3.6 and newer.10 11+``async`` support in Flask requires Python 3.7+ for ``contextvars.ContextVar``.12 13+14 Dependencies15 ------------16 17 These distributions will be installed automatically when installing Flask.118 unmodified linesmodified:docs/quickstart.rst+3 added-3 removed
442 unmodified lines443 {% else %}444 <h1>Hello, World!</h1>445 {% endif %}446 447-Inside templates you also have access to the :class:`~flask.request`,448-:class:`~flask.session` and :class:`~flask.g` [#]_ objects449-as well as the :func:`~flask.get_flashed_messages` function.447+Inside templates you also have access to the :data:`~flask.Flask.config`,448+:class:`~flask.request`, :class:`~flask.session` and :class:`~flask.g` [#]_ objects449+as well as the :func:`~flask.url_for` and :func:`~flask.get_flashed_messages` functions.450 451 Templates are especially useful if inheritance is used. If you want to452 know how that works, see :doc:`patterns/templateinheritance`. Basically453 template inheritance makes it possible to keep certain elements on each485 unmodified linesmodified:docs/templating.rst+1 added-1 removed
35 unmodified lines36 37 .. data:: config38 :noindex:39 40- The current configuration object (:data:`flask.config`)40+ The current configuration object (:data:`flask.Flask.config`)41 42 .. versionadded:: 0.643 44 .. versionchanged:: 0.10159 unmodified linesmodified:docs/testing.rst+15 added-14 removed
46 unmodified lines47 48 import pytest49 50 from flaskr import create_app51+ from flaskr.db import init_db52 53 54 @pytest.fixture55 def client():55- db_fd, flaskr.app.config['DATABASE'] = tempfile.mkstemp()56- flaskr.app.config['TESTING'] = True56+ db_fd, db_path = tempfile.mkstemp()57+ app = create_app({'TESTING': True, 'DATABASE': db_path})58 58- with flaskr.app.test_client() as client:59- with flaskr.app.app_context():60- flaskr.init_db()59+ with app.test_client() as client:60+ with app.app_context():61+ init_db()62 yield client63 64 os.close(db_fd)64- os.unlink(flaskr.app.config['DATABASE'])65+ os.unlink(db_path)66 67 This client fixture will be called by each individual test. It gives us a68 simple interface to the application, where we can trigger test requests to the69 application. The client will also keep track of cookies for us.154 unmodified lines224 temporarily. With this you can access the :class:`~flask.request`,225 :class:`~flask.g` and :class:`~flask.session` objects like in view226 functions. Here is a full example that demonstrates this approach::227 227- import flask228+ from flask import Flask, request229 229- app = flask.Flask(__name__)230+ app = Flask(__name__)231 232 with app.test_request_context('/?name=Peter'):232- assert flask.request.path == '/'233- assert flask.request.args['name'] == 'Peter'233+ assert request.path == '/'234+ assert request.args['name'] == 'Peter'235 236 All the other objects that are context bound can be used in the same237 way.238 8 unmodified lines247 the test request context leaves the ``with`` block. If you do want the248 :meth:`~flask.Flask.before_request` functions to be called as well, you249 need to call :meth:`~flask.Flask.preprocess_request` yourself::250 250- app = flask.Flask(__name__)251+ app = Flask(__name__)252 253 with app.test_request_context('/?name=Peter'):254 app.preprocess_request()255 ...4 unmodified lines260 If you want to call the :meth:`~flask.Flask.after_request` functions you261 need to call into :meth:`~flask.Flask.process_response` which however262 requires that you pass it a response object::263 263- app = flask.Flask(__name__)264+ app = Flask(__name__)265 266 with app.test_request_context('/?name=Peter'):267 resp = Response('...')268 resp = app.process_response(resp)60 unmodified lines329 context around for a little longer so that additional introspection can330 happen. With Flask 0.4 this is possible by using the331 :meth:`~flask.Flask.test_client` with a ``with`` block::332 332- app = flask.Flask(__name__)333+ app = Flask(__name__)334 335 with app.test_client() as c:336 rv = c.get('/?tequila=42')337 assert request.args['tequila'] == '42'15 unmodified lines353 keep the context around and access :data:`flask.session`::354 355 with app.test_client() as c:356 rv = c.get('/')356- assert flask.session['foo'] == 42357+ assert session['foo'] == 42358 359 This however does not make it possible to also modify the session or to360 access the session before a request was fired. Starting with Flask 0.8 we361 provide a so called “session transaction” which simulates the appropriate102 unmodified linesmodified:src/flask/app.py+5 added-3 removed
59 unmodified lines60 from .templating import Environment61 from .typing import AfterRequestCallable62 from .typing import BeforeFirstRequestCallable63 from .typing import BeforeRequestCallable64-from .typing import ErrorHandlerCallable64 from .typing import ResponseReturnValue65 from .typing import TeardownCallable66 from .typing import TemplateContextProcessorCallable67 from .typing import TemplateFilterCallable8 unmodified lines76 import typing_extensions as te77 from .blueprints import Blueprint78 from .testing import FlaskClient79 from .testing import FlaskCliRunner80+ from .typing import ErrorHandlerCallable81 82 if sys.version_info >= (3, 8):83 iscoroutinefunction = inspect.iscoroutinefunction84 else:1182 unmodified lines1267 """1268 self.shell_context_processors.append(f)1269 return f1270 1271- def _find_error_handler(self, e: Exception) -> t.Optional[ErrorHandlerCallable]:1271+ def _find_error_handler(1272+ self, e: Exception1273+ ) -> t.Optional["ErrorHandlerCallable[Exception]"]:1274 """Return a registered error handler for an exception in this order:1275 blueprint handler for a specific code, app handler for a specific code,1276 blueprint handler for an exception class, app handler for an exception1277 class, or ``None`` if a suitable handler is not found.1278 """1279 exc_class, code = self._get_exc_class_and_code(type(e))1280 1279- for c in [code, None]:1281+ for c in [code, None] if code is not None else [None]:1282 for name in chain(request.blueprints, [None]):1283 handler_map = self.error_handler_spec[name][c]1284 1285 if not handler_map:808 unmodified linesmodified:src/flask/blueprints.py+9 added-5 removed
6 unmodified lines7 from .scaffold import Scaffold8 from .typing import AfterRequestCallable9 from .typing import BeforeFirstRequestCallable10 from .typing import BeforeRequestCallable11-from .typing import ErrorHandlerCallable11 from .typing import TeardownCallable12 from .typing import TemplateContextProcessorCallable13 from .typing import TemplateFilterCallable14 from .typing import TemplateGlobalCallable2 unmodified lines17 from .typing import URLValuePreprocessorCallable18 19 if t.TYPE_CHECKING:20 from .app import Flask21+ from .typing import ErrorHandlerCallable22 23 DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]24 25 266 unmodified lines292 .. versionchanged:: 2.0.1293 Registering the same blueprint with the same name multiple294 times is deprecated and will become an error in Flask 2.1.295 """296- first_registration = not any(bp is self for bp in app.blueprints.values())296 name_prefix = options.get("name_prefix", "")297 self_name = options.get("name", self.name)298 name = f"{name_prefix}.{self_name}".lstrip(".")299 16 unmodified lines316 " in Flask 2.1.",317 stacklevel=4,318 )319 320+ first_bp_registration = not any(bp is self for bp in app.blueprints.values())321+ first_name_registration = name not in app.blueprints322+323 app.blueprints[name] = self324 self._got_registered_once = True323- state = self.make_setup_state(app, options, first_registration)325+ state = self.make_setup_state(app, options, first_bp_registration)326 327 if self.has_static_folder:328 state.add_url_rule(329 f"{self.static_url_path}/<path:filename>",1 unmodified line331 endpoint="static",332 )333 334 # Merge blueprint data into parent.333- if first_registration:335+ if first_bp_registration or first_name_registration:336 337 def extend(bp_dict, parent_dict):338 for key, values in bp_dict.items():339 key = name if key is None else f"{name}.{key}"242 unmodified lines582 """Like :meth:`Flask.errorhandler` but for a blueprint. This583 handler is used for all requests, even if outside of the blueprint.584 """585 584- def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:586+ def decorator(587+ f: "ErrorHandlerCallable[Exception]",588+ ) -> "ErrorHandlerCallable[Exception]":589 self.record_once(lambda s: s.app.errorhandler(code)(f))590 return f591 592 return decorator16 unmodified linesmodified:src/flask/scaffold.py+19 added-8 removed
19 unmodified lines20 from .templating import _default_template_ctx_processor21 from .typing import AfterRequestCallable22 from .typing import AppOrBlueprintKey23 from .typing import BeforeRequestCallable24-from .typing import ErrorHandlerCallable24+from .typing import GenericException25 from .typing import TeardownCallable26 from .typing import TemplateContextProcessorCallable27 from .typing import URLDefaultCallable28 from .typing import URLValuePreprocessorCallable29 30 if t.TYPE_CHECKING:31 from .wrappers import Response32+ from .typing import ErrorHandlerCallable33 34 # a singleton sentinel value for parameter defaults35 _sentinel = object()36 107 unmodified lines144 #: This data structure is internal. It should not be modified145 #: directly and its format may change at any time.146 self.error_handler_spec: t.Dict[147 AppOrBlueprintKey,147- t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ErrorHandlerCallable]],148+ t.Dict[149+ t.Optional[int],150+ t.Dict[t.Type[Exception], "ErrorHandlerCallable[Exception]"],151+ ],152 ] = defaultdict(lambda: defaultdict(dict))153 154 #: A data structure of functions to call at the beginning of155 #: each request, in the format ``{scope: [functions]}``. The490 unmodified lines646 return f647 648 @setupmethod649 def errorhandler(646- self, code_or_exception: t.Union[t.Type[Exception], int]647- ) -> t.Callable[[ErrorHandlerCallable], ErrorHandlerCallable]:650+ self, code_or_exception: t.Union[t.Type[GenericException], int]651+ ) -> t.Callable[652+ ["ErrorHandlerCallable[GenericException]"],653+ "ErrorHandlerCallable[GenericException]",654+ ]:655 """Register a function to handle errors by code or exception class.656 657 A decorator that is used to register a function given an658 error code. Example::21 unmodified lines680 :param code_or_exception: the code as integer for the handler, or681 an arbitrary exception682 """683 677- def decorator(f: ErrorHandlerCallable) -> ErrorHandlerCallable:684+ def decorator(685+ f: "ErrorHandlerCallable[GenericException]",686+ ) -> "ErrorHandlerCallable[GenericException]":687 self.register_error_handler(code_or_exception, f)688 return f689 690 return decorator691 692 @setupmethod693 def register_error_handler(694 self,686- code_or_exception: t.Union[t.Type[Exception], int],687- f: ErrorHandlerCallable,695+ code_or_exception: t.Union[t.Type[GenericException], int],696+ f: "ErrorHandlerCallable[GenericException]",697 ) -> None:698 """Alternative error attach function to the :meth:`errorhandler`699 decorator that is more straightforward to use for non decorator700 usage.15 unmodified lines716 " code. Use a subclass of HTTPException with that code"717 " instead."718 )719 711- self.error_handler_spec[None][code][exc_class] = f720+ self.error_handler_spec[None][code][exc_class] = t.cast(721+ "ErrorHandlerCallable[Exception]", f722+ )723 724 @staticmethod725 def _get_exc_class_and_code(726 exc_class_or_code: t.Union[t.Type[Exception], int]149 unmodified linesmodified:src/flask/typing.py+10 added-1 removed
31 unmodified lines32 t.Tuple[ResponseValue, StatusCode, HeadersValue],33 "WSGIApplication",34 ]35 36+GenericException = t.TypeVar("GenericException", bound=Exception, contravariant=True)37+38 AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named39 AfterRequestCallable = t.Callable[["Response"], "Response"]40 BeforeFirstRequestCallable = t.Callable[[], None]41 BeforeRequestCallable = t.Callable[[], t.Optional[ResponseReturnValue]]40-ErrorHandlerCallable = t.Callable[[Exception], ResponseReturnValue]42 TeardownCallable = t.Callable[[t.Optional[BaseException]], None]43 TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]44 TemplateFilterCallable = t.Callable[..., t.Any]45 TemplateGlobalCallable = t.Callable[..., t.Any]46 TemplateTestCallable = t.Callable[..., bool]47 URLDefaultCallable = t.Callable[[str, dict], None]48 URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]49+50+51+if t.TYPE_CHECKING:52+ import typing_extensions as te53+54+ class ErrorHandlerCallable(te.Protocol[GenericException]):55+ def __call__(self, error: GenericException) -> ResponseReturnValue:56+ ...modified: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:tests/test_blueprints.py+10 added
897 unmodified lines898 @bp.get("/")899 def index():900 return flask.request.endpoint901 902+ @bp.get("/error")903+ def error():904+ flask.abort(403)905+906+ @bp.errorhandler(403)907+ def forbidden(_: Exception):908+ return "Error", 403909+910 @bp2.get("/")911 def index2():912 return flask.request.endpoint913 4 unmodified lines918 assert client.get("/a/").data == b"bp.index"919 assert client.get("/b/").data == b"alt.index"920 assert client.get("/a/a/").data == b"bp.sub.index2"921 assert client.get("/b/a/").data == b"alt.sub.index2"922+ assert client.get("/a/error").data == b"Error"923+ assert client.get("/b/error").data == b"Error"modified:CHANGES.rst+4 added-1 removed
11 unmodified lines12 -------------13 14 Unreleased15 16-- Fix type annotation for ``teardown_request``. :issue:`4093`16+- Fix type annotation for ``teardown_*`` methods. :issue:`4093`17 - Fix type annotation for ``before_request`` and ``before_app_request``18 decorators. :issue:`4104`19 - Fixed the issue where typing requires template global20 decorators to accept functions with no arguments. :issue:`4098`21+- Support View and MethodView instances with async handlers. :issue:`4112`22+- Enhance typing of ``app.errorhandler`` decorator. :issue:`4095`23+- Fix registering a blueprint twice with differing names. :issue:`4124`24 25 26 Version 2.0.127 -------------1154 unmodified linesmodified:CONTRIBUTING.rst+4 added-2 removed
10 unmodified lines11 to address bugs and feature requests in Flask itself. Use one of the12 following resources for questions about using Flask or issues with your13 own code:14 15-- The ``#get-help`` channel on our Discord chat:15+- The ``#questions`` channel on our Discord chat:16 https://discord.gg/pallets17 - The mailing list flask@python.org for long term discussion or larger18 issues.19 - Ask on `Stack Overflow`_. Search with Google first using:20 ``site:stackoverflow.com flask {search term, exception message, etc.}``21+- Ask on our `GitHub Discussions`_.22 23 .. _Stack Overflow: https://stackoverflow.com/questions/tagged/flask?tab=Frequent24+.. _GitHub Discussions: https://github.com/pallets/flask/discussions25 26 27 Reporting issues28 ----------------64 unmodified lines93 default Pallets remote is "origin".94 95 .. code-block:: text96 95- git remote add fork https://github.com/{username}/flask97+ $ git remote add fork https://github.com/{username}/flask98 99 - Create a virtualenv.100 101 .. tabs::128 unmodified lines