Merge branch '2.1.x'
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 · parents c6e3fc8, 21d32ee · Browse files · 11 files·+118 added−116 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+118 added−116 removed
- other:+118 added−116 removed
Provenance
- Commit
9e2e1de- Tree
b4f4aa5- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
c6e3fc8- Parent 2
21d32ee
11 files changed+118 added−116 removed
modified:docs/patterns/celery.rst+15 added-11 removed
32 unmodified lines33 Celery without any reconfiguration with Flask, it becomes a bit nicer by34 subclassing tasks and adding support for Flask's application contexts and35 hooking it up with the Flask configuration.36 37-This is all that is necessary to properly integrate Celery with Flask::37+This is all that is necessary to integrate Celery with Flask:38 39+.. code-block:: python40+41 from celery import Celery42 43 def make_celery(app):42- celery = Celery(43- app.import_name,44- backend=app.config['CELERY_RESULT_BACKEND'],45- broker=app.config['CELERY_BROKER_URL']46- )47- celery.conf.update(app.config)44+ celery = Celery(app.import_name)45+ celery.conf.update(app.config["CELERY_CONFIG"])46 47 class ContextTask(celery.Task):48 def __call__(self, *args, **kwargs):49 with app.app_context():6 unmodified lines56 from the application config, updates the rest of the Celery config from57 the Flask config and then creates a subclass of the task that wraps the58 task execution in an application context.59 60+.. note::61+ Celery 5.x deprecated uppercase configuration keys, and 6.x will62+ remove them. See their official `migration guide`_.63+64+.. _migration guide: https://docs.celeryproject.org/en/stable/userguide/configuration.html#conf-old-settings-map.65+66 An example task67 ---------------68 69 Let's write a task that adds two numbers together and returns the result. We2 unmodified lines72 73 from flask import Flask74 75 flask_app = Flask(__name__)72- flask_app.config.update(73- CELERY_BROKER_URL='redis://localhost:6379',74- CELERY_RESULT_BACKEND='redis://localhost:6379'75- )76+ flask_app.config.update(CELERY_CONFIG={77+ 'broker_url': 'redis://localhost:6379',78+ 'result_backend': 'redis://localhost:6379',79+ })80 celery = make_celery(flask_app)81 82 @celery.task()83 def add_together(a, b):22 unmodified linesmodified:docs/tutorial/install.rst+4 added-2 removed
65 unmodified lines66 This tells Python to copy everything in the ``static`` and ``templates``67 directories, and the ``schema.sql`` file, but to exclude all bytecode68 files.69 70-See the `official packaging guide`_ for another explanation of the files70+See the official `Packaging tutorial <packaging tutorial_>`_ and71+`detailed guide <packaging guide_>`_ for more explanation of the files72 and options used.73 73-.. _official packaging guide: https://packaging.python.org/tutorials/packaging-projects/74+.. _packaging tutorial: https://packaging.python.org/tutorials/packaging-projects/75+.. _packaging guide: https://packaging.python.org/guides/distributing-packages-using-setuptools/76 77 78 Install the Project79 -------------------37 unmodified linesmodified:requirements/dev.txt+2 added-2 removed
14 unmodified lines15 # pip-compile-multi16 # pip-tools17 distlib==0.3.418 # via virtualenv19-filelock==3.7.019+filelock==3.7.120 # via21 # tox22 # virtualenv23 greenlet==1.1.2 ; python_version < "3.11"5 unmodified lines29 pep517==0.12.030 # via pip-tools31 pip-compile-multi==2.4.532 # via -r requirements/dev.in33-pip-tools==6.6.133+pip-tools==6.6.234 # via pip-compile-multi35 platformdirs==2.5.236 # via virtualenv37 pre-commit==2.19.025 unmodified linesmodified:requirements/typing.txt+3 added-3 removed
7 unmodified lines8 cffi==1.15.09 # via cryptography10 cryptography==37.0.211 # via -r requirements/typing.in12-mypy==0.95012+mypy==0.96013 # via -r requirements/typing.in14 mypy-extensions==0.4.315 # via mypy16 pycparser==2.2117 # via cffi18 tomli==2.0.119 # via mypy20-types-contextvars==2.4.520+types-contextvars==2.4.621 # via -r requirements/typing.in22 types-dataclasses==0.6.523 # via -r requirements/typing.in24-types-setuptools==57.4.1524+types-setuptools==57.4.1725 # via -r requirements/typing.in26 typing-extensions==4.2.027 # via mypymodified:src/flask/app.py+26 added-30 removed
27 unmodified lines28 from werkzeug.wrappers import Response as BaseResponse29 30 from . import cli31 from . import json32+from . import typing as ft33 from .config import Config34 from .config import ConfigAttribute35 from .ctx import _AppCtxGlobals36 from .ctx import AppContext24 unmodified lines61 from .signals import request_started62 from .signals import request_tearing_down63 from .templating import DispatchingJinjaLoader64 from .templating import Environment64-from .typing import BeforeFirstRequestCallable65-from .typing import ResponseReturnValue66-from .typing import TeardownCallable67-from .typing import TemplateFilterCallable68-from .typing import TemplateGlobalCallable69-from .typing import TemplateTestCallable65 from .wrappers import Request66 from .wrappers import Response67 68 if t.TYPE_CHECKING: # pragma: no cover69 import typing_extensions as te70 from .blueprints import Blueprint71 from .testing import FlaskClient72 from .testing import FlaskCliRunner78- from .typing import ErrorHandlerCallable73 74 if sys.version_info >= (3, 8):75 iscoroutinefunction = inspect.iscoroutinefunction76 else:374 unmodified lines451 #: first request to this instance. To register a function, use the452 #: :meth:`before_first_request` decorator.453 #:454 #: .. versionadded:: 0.8461- self.before_first_request_funcs: t.List[BeforeFirstRequestCallable] = []455+ self.before_first_request_funcs: t.List[ft.BeforeFirstRequestCallable] = []456 457 #: A list of functions that are called when the application context458 #: is destroyed. Since the application context is also torn down459 #: if the request ends this is the place to store code that disconnects460 #: from databases.461 #:462 #: .. versionadded:: 0.9469- self.teardown_appcontext_funcs: t.List[TeardownCallable] = []463+ self.teardown_appcontext_funcs: t.List[ft.TeardownCallable] = []464 465 #: A list of shell context processor functions that should be run466 #: when a shell context is created.467 #:664 unmodified lines1132 1133 @setupmethod1134 def template_filter(1135 self, name: t.Optional[str] = None1142- ) -> t.Callable[[TemplateFilterCallable], TemplateFilterCallable]:1136+ ) -> t.Callable[[ft.TemplateFilterCallable], ft.TemplateFilterCallable]:1137 """A decorator that is used to register custom template filter.1138 You can specify a name for the filter, otherwise the function1139 name will be used. Example::1140 4 unmodified lines1145 :param name: the optional name of the filter, otherwise the1146 function name will be used.1147 """1148 1155- def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:1149+ def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable:1150 self.add_template_filter(f, name=name)1151 return f1152 1153 return decorator1154 1155 @setupmethod1156 def add_template_filter(1163- self, f: TemplateFilterCallable, name: t.Optional[str] = None1157+ self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None1158 ) -> None:1159 """Register a custom template filter. Works exactly like the1160 :meth:`template_filter` decorator.1161 4 unmodified lines1166 1167 @setupmethod1168 def template_test(1169 self, name: t.Optional[str] = None1176- ) -> t.Callable[[TemplateTestCallable], TemplateTestCallable]:1170+ ) -> t.Callable[[ft.TemplateTestCallable], ft.TemplateTestCallable]:1171 """A decorator that is used to register custom template test.1172 You can specify a name for the test, otherwise the function1173 name will be used. Example::1174 11 unmodified lines1186 :param name: the optional name of the test, otherwise the1187 function name will be used.1188 """1189 1196- def decorator(f: TemplateTestCallable) -> TemplateTestCallable:1190+ def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable:1191 self.add_template_test(f, name=name)1192 return f1193 1194 return decorator1195 1196 @setupmethod1197 def add_template_test(1204- self, f: TemplateTestCallable, name: t.Optional[str] = None1198+ self, f: ft.TemplateTestCallable, name: t.Optional[str] = None1199 ) -> None:1200 """Register a custom template test. Works exactly like the1201 :meth:`template_test` decorator.1202 6 unmodified lines1209 1210 @setupmethod1211 def template_global(1212 self, name: t.Optional[str] = None1219- ) -> t.Callable[[TemplateGlobalCallable], TemplateGlobalCallable]:1213+ ) -> t.Callable[[ft.TemplateGlobalCallable], ft.TemplateGlobalCallable]:1214 """A decorator that is used to register a custom template global function.1215 You can specify a name for the global function, otherwise the function1216 name will be used. Example::1217 6 unmodified lines1224 :param name: the optional name of the global function, otherwise the1225 function name will be used.1226 """1227 1234- def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:1228+ def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable:1229 self.add_template_global(f, name=name)1230 return f1231 1232 return decorator1233 1234 @setupmethod1235 def add_template_global(1242- self, f: TemplateGlobalCallable, name: t.Optional[str] = None1236+ self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None1237 ) -> None:1238 """Register a custom template global function. Works exactly like the1239 :meth:`template_global` decorator.1240 5 unmodified lines1246 self.jinja_env.globals[name or f.__name__] = f1247 1248 @setupmethod1249 def before_first_request(1256- self, f: BeforeFirstRequestCallable1257- ) -> BeforeFirstRequestCallable:1250+ self, f: ft.BeforeFirstRequestCallable1251+ ) -> ft.BeforeFirstRequestCallable:1252 """Registers a function to be run before the first request to this1253 instance of the application.1254 1255 The function will be called without any arguments and its return4 unmodified lines1260 self.before_first_request_funcs.append(f)1261 return f1262 1263 @setupmethod1270- def teardown_appcontext(self, f: TeardownCallable) -> TeardownCallable:1264+ def teardown_appcontext(self, f: ft.TeardownCallable) -> ft.TeardownCallable:1265 """Registers a function to be called when the application context1266 ends. These functions are typically also called when the request1267 context is popped.1268 32 unmodified lines1301 """1302 self.shell_context_processors.append(f)1303 return f1304 1311- def _find_error_handler(self, e: Exception) -> t.Optional["ErrorHandlerCallable"]:1305+ def _find_error_handler(self, e: Exception) -> t.Optional[ft.ErrorHandlerCallable]:1306 """Return a registered error handler for an exception in this order:1307 blueprint handler for a specific code, app handler for a specific code,1308 blueprint handler for an exception class, app handler for an exception1309 class, or ``None`` if a suitable handler is not found.16 unmodified lines1326 return None1327 1328 def handle_http_exception(1329 self, e: HTTPException1336- ) -> t.Union[HTTPException, ResponseReturnValue]:1330+ ) -> t.Union[HTTPException, ft.ResponseReturnValue]:1331 """Handles an HTTP exception. By default this will invoke the1332 registered error handlers and fall back to returning the1333 exception as response.1334 61 unmodified lines1396 return False1397 1398 def handle_user_exception(1399 self, e: Exception1406- ) -> t.Union[HTTPException, ResponseReturnValue]:1400+ ) -> t.Union[HTTPException, ft.ResponseReturnValue]:1401 """This method is called whenever an exception occurs that1402 should be handled. A special case is :class:`~werkzeug1403 .exceptions.HTTPException` which is forwarded to the1404 :meth:`handle_http_exception` method. This function will either61 unmodified lines1466 1467 raise e1468 1469 self.log_exception(exc_info)1476- server_error: t.Union[InternalServerError, ResponseReturnValue]1470+ server_error: t.Union[InternalServerError, ft.ResponseReturnValue]1471 server_error = InternalServerError(original_exception=e)1472 handler = self._find_error_handler(server_error)1473 1474 if handler is not None:45 unmodified lines1520 from .debughelpers import FormDataRoutingRedirect1521 1522 raise FormDataRoutingRedirect(request)1523 1530- def dispatch_request(self) -> ResponseReturnValue:1524+ def dispatch_request(self) -> ft.ResponseReturnValue:1525 """Does the request dispatching. Matches the URL and returns the1526 return value of the view or error handler. This does not have to1527 be a response object. In order to convert the return value to a1528 proper response object, call :func:`make_response`.34 unmodified lines1563 return self.finalize_request(rv)1564 1565 def finalize_request(1566 self,1573- rv: t.Union[ResponseReturnValue, HTTPException],1567+ rv: t.Union[ft.ResponseReturnValue, HTTPException],1568 from_error_handler: bool = False,1569 ) -> Response:1570 """Given the return value from a view function this finalizes1571 the request by converting it into a response and invoking the232 unmodified lines1804 Moved from ``flask.redirect``, which calls this method.1805 """1806 return _wz_redirect(location, code=code, Response=self.response_class)1807 1814- def make_response(self, rv: ResponseReturnValue) -> Response:1808+ def make_response(self, rv: ft.ResponseReturnValue) -> Response:1809 """Convert the return value from a view function to an instance of1810 :attr:`response_class`.1811 1812 :param rv: the return value from the view function. The view function83 unmodified lines1896 elif isinstance(rv, BaseResponse) or callable(rv):1897 # evaluate a WSGI callable, or coerce a different response1898 # class to the correct type1899 try:1906- rv = self.response_class.force_type(rv, request.environ) # type: ignore # noqa: B9501900+ rv = self.response_class.force_type(1901+ rv, request.environ # type: ignore[arg-type]1902+ )1903 except TypeError as e:1904 raise TypeError(1905 f"{e}\nThe view function did not return a valid"1906 " response. The return type must be a string,"118 unmodified lines2025 raise2026 2027 raise error2028 2033- def preprocess_request(self) -> t.Optional[ResponseReturnValue]:2029+ def preprocess_request(self) -> t.Optional[ft.ResponseReturnValue]:2030 """Called before the request is dispatched. Calls2031 :attr:`url_value_preprocessors` registered with the app and the2032 current blueprint (if any). Then calls :attr:`before_request_funcs`2033 registered with the app and the blueprint.250 unmodified linesmodified:src/flask/blueprints.py+23 added-31 removed
1 unmodified line2 import typing as t3 from collections import defaultdict4 from functools import update_wrapper5 6+from . import typing as ft7 from .scaffold import _endpoint_from_view_func8 from .scaffold import _sentinel9 from .scaffold import Scaffold10 from .scaffold import setupmethod10-from .typing import AfterRequestCallable11-from .typing import BeforeFirstRequestCallable12-from .typing import BeforeRequestCallable13-from .typing import TeardownCallable14-from .typing import TemplateContextProcessorCallable15-from .typing import TemplateFilterCallable16-from .typing import TemplateGlobalCallable17-from .typing import TemplateTestCallable18-from .typing import URLDefaultCallable19-from .typing import URLValuePreprocessorCallable11 12 if t.TYPE_CHECKING: # pragma: no cover13 from .app import Flask23- from .typing import ErrorHandlerCallable14 15 DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]16 17 399 unmodified lines417 418 @setupmethod419 def app_template_filter(420 self, name: t.Optional[str] = None431- ) -> t.Callable[[TemplateFilterCallable], TemplateFilterCallable]:421+ ) -> t.Callable[[ft.TemplateFilterCallable], ft.TemplateFilterCallable]:422 """Register a custom template filter, available application wide. Like423 :meth:`Flask.template_filter` but for a blueprint.424 425 :param name: the optional name of the filter, otherwise the426 function name will be used.427 """428 439- def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:429+ def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable:430 self.add_app_template_filter(f, name=name)431 return f432 433 return decorator434 435 @setupmethod436 def add_app_template_filter(447- self, f: TemplateFilterCallable, name: t.Optional[str] = None437+ self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None438 ) -> None:439 """Register a custom template filter, available application wide. Like440 :meth:`Flask.add_template_filter` but for a blueprint. Works exactly441 like the :meth:`app_template_filter` decorator.9 unmodified lines451 452 @setupmethod453 def app_template_test(454 self, name: t.Optional[str] = None465- ) -> t.Callable[[TemplateTestCallable], TemplateTestCallable]:455+ ) -> t.Callable[[ft.TemplateTestCallable], ft.TemplateTestCallable]:456 """Register a custom template test, available application wide. Like457 :meth:`Flask.template_test` but for a blueprint.458 459 .. versionadded:: 0.101 unmodified line461 :param name: the optional name of the test, otherwise the462 function name will be used.463 """464 475- def decorator(f: TemplateTestCallable) -> TemplateTestCallable:465+ def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable:466 self.add_app_template_test(f, name=name)467 return f468 469 return decorator470 471 @setupmethod472 def add_app_template_test(483- self, f: TemplateTestCallable, name: t.Optional[str] = None473+ self, f: ft.TemplateTestCallable, name: t.Optional[str] = None474 ) -> None:475 """Register a custom template test, available application wide. Like476 :meth:`Flask.add_template_test` but for a blueprint. Works exactly477 like the :meth:`app_template_test` decorator.11 unmodified lines489 490 @setupmethod491 def app_template_global(492 self, name: t.Optional[str] = None503- ) -> t.Callable[[TemplateGlobalCallable], TemplateGlobalCallable]:493+ ) -> t.Callable[[ft.TemplateGlobalCallable], ft.TemplateGlobalCallable]:494 """Register a custom template global, available application wide. Like495 :meth:`Flask.template_global` but for a blueprint.496 497 .. versionadded:: 0.101 unmodified line499 :param name: the optional name of the global, otherwise the500 function name will be used.501 """502 513- def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:503+ def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable:504 self.add_app_template_global(f, name=name)505 return f506 507 return decorator508 509 @setupmethod510 def add_app_template_global(521- self, f: TemplateGlobalCallable, name: t.Optional[str] = None511+ self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None512 ) -> None:513 """Register a custom template global, available application wide. Like514 :meth:`Flask.add_template_global` but for a blueprint. Works exactly515 like the :meth:`app_template_global` decorator.9 unmodified lines525 526 self.record_once(register_template)527 528 @setupmethod539- def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:529+ def before_app_request(530+ self, f: ft.BeforeRequestCallable531+ ) -> ft.BeforeRequestCallable:532 """Like :meth:`Flask.before_request`. Such a function is executed533 before each request, even if outside of a blueprint.534 """535 self.record_once(2 unmodified lines538 return f539 540 @setupmethod541 def before_app_first_request(550- self, f: BeforeFirstRequestCallable551- ) -> BeforeFirstRequestCallable:542+ self, f: ft.BeforeFirstRequestCallable543+ ) -> ft.BeforeFirstRequestCallable:544 """Like :meth:`Flask.before_first_request`. Such a function is545 executed before the first request to the application.546 """547 self.record_once(lambda s: s.app.before_first_request_funcs.append(f))548 return f549 558- def after_app_request(self, f: AfterRequestCallable) -> AfterRequestCallable:550+ def after_app_request(self, f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:551 """Like :meth:`Flask.after_request` but for a blueprint. Such a function552 is executed after each request, even if outside of the blueprint.553 """554 self.record_once(1 unmodified line556 )557 return f558 559 @setupmethod568- def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable:560+ def teardown_app_request(self, f: ft.TeardownCallable) -> ft.TeardownCallable:561 """Like :meth:`Flask.teardown_request` but for a blueprint. Such a562 function is executed when tearing down each request, even if outside of563 the blueprint.564 """3 unmodified lines568 return f569 570 @setupmethod571 def app_context_processor(580- self, f: TemplateContextProcessorCallable581- ) -> TemplateContextProcessorCallable:572+ self, f: ft.TemplateContextProcessorCallable573+ ) -> ft.TemplateContextProcessorCallable:574 """Like :meth:`Flask.context_processor` but for a blueprint. Such a575 function is executed each request, even if outside of the blueprint.576 """577 self.record_once(6 unmodified lines584 """Like :meth:`Flask.errorhandler` but for a blueprint. This585 handler is used for all requests, even if outside of the blueprint.586 """587 596- def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":588+ def decorator(f: ft.ErrorHandlerCallable) -> ft.ErrorHandlerCallable:589 self.record_once(lambda s: s.app.errorhandler(code)(f))590 return f591 592 return decorator593 594 @setupmethod595 def app_url_value_preprocessor(604- self, f: URLValuePreprocessorCallable605- ) -> URLValuePreprocessorCallable:596+ self, f: ft.URLValuePreprocessorCallable597+ ) -> ft.URLValuePreprocessorCallable:598 """Same as :meth:`url_value_preprocessor` but application wide."""599 self.record_once(600 lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)601 )602 return f603 604 @setupmethod613- def app_url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:605+ def app_url_defaults(self, f: ft.URLDefaultCallable) -> ft.URLDefaultCallable:606 """Same as :meth:`url_defaults` but application wide."""607 self.record_once(608 lambda s: s.app.url_default_functions.setdefault(None, []).append(f)609 )1 unmodified linemodified:src/flask/ctx.py+3 added-3 removed
3 unmodified lines4 from types import TracebackType5 6 from werkzeug.exceptions import HTTPException7 8+from . import typing as ft9 from .globals import _app_ctx_stack10 from .globals import _request_ctx_stack11 from .signals import appcontext_popped12 from .signals import appcontext_pushed12-from .typing import AfterRequestCallable13 14 if t.TYPE_CHECKING: # pragma: no cover15 from .app import Flask16 from .sessions import SessionMixin91 unmodified lines108 return f"<flask.g of {top.app.name!r}>"109 return object.__repr__(self)110 111 112-def after_this_request(f: AfterRequestCallable) -> AfterRequestCallable:112+def after_this_request(f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:113 """Executes a function after this request. This is useful to modify114 response objects. The function is passed the response object and has115 to return the same or a new one.116 223 unmodified lines340 341 # Functions that should be executed after the request on the response342 # object. These will be called before the regular "after_request"343 # functions.344- self._after_request_functions: t.List[AfterRequestCallable] = []344+ self._after_request_functions: t.List[ft.AfterRequestCallable] = []345 346 @property347 def g(self) -> _AppCtxGlobals:348 import warnings165 unmodified linesmodified:src/flask/scaffold.py+21 added-28 removed
10 unmodified lines11 from jinja2 import FileSystemLoader12 from werkzeug.exceptions import default_exceptions13 from werkzeug.exceptions import HTTPException14 15+from . import typing as ft16 from .cli import AppGroup17 from .globals import current_app18 from .helpers import get_root_path19 from .helpers import locked_cached_property20 from .helpers import send_from_directory21 from .templating import _default_template_ctx_processor21-from .typing import AfterRequestCallable22-from .typing import AppOrBlueprintKey23-from .typing import BeforeRequestCallable24-from .typing import TeardownCallable25-from .typing import TemplateContextProcessorCallable26-from .typing import URLDefaultCallable27-from .typing import URLValuePreprocessorCallable22 23 if t.TYPE_CHECKING: # pragma: no cover30- from .typing import ErrorHandlerCallable24 from .wrappers import Response25 26 # a singleton sentinel value for parameter defaults27 _sentinel = object()95 unmodified lines123 #:124 #: This data structure is internal. It should not be modified125 #: directly and its format may change at any time.126 self.error_handler_spec: t.Dict[134- AppOrBlueprintKey,135- t.Dict[t.Optional[int], t.Dict[t.Type[Exception], "ErrorHandlerCallable"]],127+ ft.AppOrBlueprintKey,128+ t.Dict[t.Optional[int], t.Dict[t.Type[Exception], ft.ErrorHandlerCallable]],129 ] = defaultdict(lambda: defaultdict(dict))130 131 #: A data structure of functions to call at the beginning of132 #: each request, in the format ``{scope: [functions]}``. The5 unmodified lines138 #:139 #: This data structure is internal. It should not be modified140 #: directly and its format may change at any time.141 self.before_request_funcs: t.Dict[149- AppOrBlueprintKey, t.List[BeforeRequestCallable]142+ ft.AppOrBlueprintKey, t.List[ft.BeforeRequestCallable]143 ] = defaultdict(list)144 145 #: A data structure of functions to call at the end of each146 #: request, in the format ``{scope: [functions]}``. The5 unmodified lines152 #:153 #: This data structure is internal. It should not be modified154 #: directly and its format may change at any time.155 self.after_request_funcs: t.Dict[163- AppOrBlueprintKey, t.List[AfterRequestCallable]156+ ft.AppOrBlueprintKey, t.List[ft.AfterRequestCallable]157 ] = defaultdict(list)158 159 #: A data structure of functions to call at the end of each160 #: request even if an exception is raised, in the format6 unmodified lines167 #:168 #: This data structure is internal. It should not be modified169 #: directly and its format may change at any time.170 self.teardown_request_funcs: t.Dict[178- AppOrBlueprintKey, t.List[TeardownCallable]171+ ft.AppOrBlueprintKey, t.List[ft.TeardownCallable]172 ] = defaultdict(list)173 174 #: A data structure of functions to call to pass extra context175 #: values when rendering templates, in the format6 unmodified lines182 #:183 #: This data structure is internal. It should not be modified184 #: directly and its format may change at any time.185 self.template_context_processors: t.Dict[193- AppOrBlueprintKey, t.List[TemplateContextProcessorCallable]186+ ft.AppOrBlueprintKey, t.List[ft.TemplateContextProcessorCallable]187 ] = defaultdict(list, {None: [_default_template_ctx_processor]})188 189 #: A data structure of functions to call to modify the keyword190 #: arguments passed to the view function, in the format6 unmodified lines197 #:198 #: This data structure is internal. It should not be modified199 #: directly and its format may change at any time.200 self.url_value_preprocessors: t.Dict[208- AppOrBlueprintKey,209- t.List[URLValuePreprocessorCallable],201+ ft.AppOrBlueprintKey,202+ t.List[ft.URLValuePreprocessorCallable],203 ] = defaultdict(list)204 205 #: A data structure of functions to call to modify the keyword206 #: arguments when generating URLs, in the format6 unmodified lines213 #:214 #: This data structure is internal. It should not be modified215 #: directly and its format may change at any time.216 self.url_default_functions: t.Dict[224- AppOrBlueprintKey, t.List[URLDefaultCallable]217+ ft.AppOrBlueprintKey, t.List[ft.URLDefaultCallable]218 ] = defaultdict(list)219 220 def __repr__(self) -> str:221 return f"<{type(self).__name__} {self.name!r}>"299 unmodified lines521 522 return decorator523 524 @setupmethod532- def before_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:525+ def before_request(self, f: ft.BeforeRequestCallable) -> ft.BeforeRequestCallable:526 """Register a function to run before each request.527 528 For example, this can be used to open a database connection, or529 to load the logged in user from the session.13 unmodified lines543 self.before_request_funcs.setdefault(None, []).append(f)544 return f545 546 @setupmethod554- def after_request(self, f: AfterRequestCallable) -> AfterRequestCallable:547+ def after_request(self, f: ft.AfterRequestCallable) -> ft.AfterRequestCallable:548 """Register a function to run after each request to this object.549 550 The function is called with the response object, and must return551 a response object. This allows the functions to modify or7 unmodified lines559 self.after_request_funcs.setdefault(None, []).append(f)560 return f561 562 @setupmethod570- def teardown_request(self, f: TeardownCallable) -> TeardownCallable:563+ def teardown_request(self, f: ft.TeardownCallable) -> ft.TeardownCallable:564 """Register a function to be run at the end of each request,565 regardless of whether there was an exception or not. These functions566 are executed when the request context is popped, even if not an567 actual request was performed.31 unmodified lines599 return f600 601 @setupmethod602 def context_processor(610- self, f: TemplateContextProcessorCallable611- ) -> TemplateContextProcessorCallable:603+ self, f: ft.TemplateContextProcessorCallable604+ ) -> ft.TemplateContextProcessorCallable:605 """Registers a template context processor function."""606 self.template_context_processors[None].append(f)607 return f608 609 @setupmethod610 def url_value_preprocessor(618- self, f: URLValuePreprocessorCallable619- ) -> URLValuePreprocessorCallable:611+ self, f: ft.URLValuePreprocessorCallable612+ ) -> ft.URLValuePreprocessorCallable:613 """Register a URL value preprocessor function for all view614 functions in the application. These functions will be called before the615 :meth:`before_request` functions.616 8 unmodified lines625 self.url_value_preprocessors[None].append(f)626 return f627 628 @setupmethod636- def url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:629+ def url_defaults(self, f: ft.URLDefaultCallable) -> ft.URLDefaultCallable:630 """Callback function for URL defaults for all view functions of the631 application. It's called with the endpoint and values and should632 update the values passed in place.633 """2 unmodified lines636 637 @setupmethod638 def errorhandler(639 self, code_or_exception: t.Union[t.Type[Exception], int]647- ) -> t.Callable[["ErrorHandlerCallable"], "ErrorHandlerCallable"]:640+ ) -> t.Callable[[ft.ErrorHandlerCallable], ft.ErrorHandlerCallable]:641 """Register a function to handle errors by code or exception class.642 643 A decorator that is used to register a function given an644 error code. Example::21 unmodified lines666 :param code_or_exception: the code as integer for the handler, or667 an arbitrary exception668 """669 677- def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":670+ def decorator(f: ft.ErrorHandlerCallable) -> ft.ErrorHandlerCallable:671 self.register_error_handler(code_or_exception, f)672 return f673 674 return decorator1 unmodified line676 @setupmethod677 def register_error_handler(678 self,679 code_or_exception: t.Union[t.Type[Exception], int],687- f: "ErrorHandlerCallable",680+ f: ft.ErrorHandlerCallable,681 ) -> None:682 """Alternative error attach function to the :meth:`errorhandler`683 decorator that is more straightforward to use for non decorator684 usage.176 unmodified linesmodified:src/flask/typing.py+7 added-2 removed
2 unmodified lines3 4 if t.TYPE_CHECKING: # pragma: no cover5 from _typeshed.wsgi import WSGIApplication # noqa: F4016 from werkzeug.datastructures import Headers # noqa: F4017- from werkzeug.wrappers.response import Response # noqa: F4017+ from werkzeug.wrappers import Response # noqa: F4018 9 # The possible types that are directly convertible or are a Response object.10 ResponseValue = t.Union[11 "Response",22 unmodified lines34 t.Tuple[ResponseValue, StatusCode, HeadersValue],35 "WSGIApplication",36 ]37 38+# Allow any subclass of werkzeug.Response, such as the one from Flask,39+# as a callback argument. Using werkzeug.Response directly makes a40+# callback annotated with flask.Response fail type checking.41+ResponseClass = t.TypeVar("ResponseClass", bound="Response")42+43 AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named39-AfterRequestCallable = t.Callable[["Response"], "Response"]44+AfterRequestCallable = t.Callable[[ResponseClass], ResponseClass]45 BeforeFirstRequestCallable = t.Callable[[], None]46 BeforeRequestCallable = t.Callable[[], t.Optional[ResponseReturnValue]]47 TeardownCallable = t.Callable[[t.Optional[BaseException]], None]48 TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]12 unmodified linesmodified:src/flask/views.py+4 added-4 removed
1 import typing as t2 3+from . import typing as ft4 from .globals import current_app5 from .globals import request5-from .typing import ResponseReturnValue6 7 8 http_method_funcs = frozenset(9 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]48 unmodified lines58 #:59 #: .. versionadded:: 0.860 decorators: t.List[t.Callable] = []61 62- def dispatch_request(self) -> ResponseReturnValue:62+ def dispatch_request(self) -> ft.ResponseReturnValue:63 """Subclasses have to override this method to implement the64 actual view function code. This method is called with all65 the arguments from the URL rule.66 """11 unmodified lines78 The arguments passed to :meth:`as_view` are forwarded to the79 constructor of the class.80 """81 82- def view(*args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:82+ def view(*args: t.Any, **kwargs: t.Any) -> ft.ResponseReturnValue:83 self = view.view_class(*class_args, **class_kwargs) # type: ignore84 return current_app.ensure_sync(self.dispatch_request)(*args, **kwargs)85 86 if cls.decorators:58 unmodified lines145 146 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))147 """148 149- def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ResponseReturnValue:149+ def dispatch_request(self, *args: t.Any, **kwargs: t.Any) -> ft.ResponseReturnValue:150 meth = getattr(self, request.method.lower(), None)151 152 # If the request method is HEAD and we don't have a handler for it153 # retry with GET.5 unmodified linesmodified:CHANGES.rst+10 added
20 unmodified lines21 this will become an error just like the application setup methods.22 :issue:`4571`23 24 25+Version 2.1.326+-------------27+28+Unreleased29+30+- Inline some optional imports that are only used for certain CLI31+ commands. :pr:`4606`32+- Relax type annotation for ``after_request`` functions. :issue:`4600`33+34+35 Version 2.1.236 -------------37 38 Released 2022-04-281278 unmodified lines