Skip to content
Myr

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

11 files+118 added−116 removed

modified:docs/patterns/celery.rst+15 added-11 removed
32 unmodified lines
33Celery without any reconfiguration with Flask, it becomes a bit nicer by34subclassing tasks and adding support for Flask's application contexts and35hooking it up with the Flask configuration.3637This is all that is necessary to properly integrate Celery with Flask::37This is all that is necessary to integrate Celery with Flask:3839.. code-block:: python4041 from celery import Celery4243 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"])4647 class ContextTask(celery.Task):48 def __call__(self, *args, **kwargs):49 with app.app_context():
6 unmodified lines
56from the application config, updates the rest of the Celery config from57the Flask config and then creates a subclass of the task that wraps the58task execution in an application context.5960.. note::61 Celery 5.x deprecated uppercase configuration keys, and 6.x will62 remove them. See their official `migration guide`_.6364.. _migration guide: https://docs.celeryproject.org/en/stable/userguide/configuration.html#conf-old-settings-map.6566An example task67---------------6869Let's write a task that adds two numbers together and returns the result. We
2 unmodified lines
7273 from flask import Flask7475 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)8182 @celery.task()83 def add_together(a, b):
22 unmodified lines
modified:docs/tutorial/install.rst+4 added-2 removed
65 unmodified lines
66This tells Python to copy everything in the ``static`` and ``templates``67directories, and the ``schema.sql`` file, but to exclude all bytecode68files.6970See the `official packaging guide`_ for another explanation of the files70See the official `Packaging tutorial <packaging tutorial_>`_ and71`detailed guide <packaging guide_>`_ for more explanation of the files72and options used.7373.. _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/767778Install the Project79-------------------
37 unmodified lines
modified:requirements/dev.txt+2 added-2 removed
14 unmodified lines
15 # pip-compile-multi16 # pip-tools17distlib==0.3.418 # via virtualenv19filelock==3.7.019filelock==3.7.120 # via21 # tox22 # virtualenv23greenlet==1.1.2 ; python_version < "3.11"
5 unmodified lines
29pep517==0.12.030 # via pip-tools31pip-compile-multi==2.4.532 # via -r requirements/dev.in33pip-tools==6.6.133pip-tools==6.6.234 # via pip-compile-multi35platformdirs==2.5.236 # via virtualenv37pre-commit==2.19.0
25 unmodified lines
modified:requirements/typing.txt+3 added-3 removed
7 unmodified lines
8cffi==1.15.09 # via cryptography10cryptography==37.0.211 # via -r requirements/typing.in12mypy==0.95012mypy==0.96013 # via -r requirements/typing.in14mypy-extensions==0.4.315 # via mypy16pycparser==2.2117 # via cffi18tomli==2.0.119 # via mypy20types-contextvars==2.4.520types-contextvars==2.4.621 # via -r requirements/typing.in22types-dataclasses==0.6.523 # via -r requirements/typing.in24types-setuptools==57.4.1524types-setuptools==57.4.1725 # via -r requirements/typing.in26typing-extensions==4.2.027 # via mypy
modified:src/flask/app.py+26 added-30 removed
27 unmodified lines
28from werkzeug.wrappers import Response as BaseResponse2930from . import cli31from . import json32from . import typing as ft33from .config import Config34from .config import ConfigAttribute35from .ctx import _AppCtxGlobals36from .ctx import AppContext
24 unmodified lines
61from .signals import request_started62from .signals import request_tearing_down63from .templating import DispatchingJinjaLoader64from .templating import Environment64from .typing import BeforeFirstRequestCallable65from .typing import ResponseReturnValue66from .typing import TeardownCallable67from .typing import TemplateFilterCallable68from .typing import TemplateGlobalCallable69from .typing import TemplateTestCallable65from .wrappers import Request66from .wrappers import Response6768if 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 ErrorHandlerCallable7374if sys.version_info >= (3, 8):75 iscoroutinefunction = inspect.iscoroutinefunction76else:
374 unmodified lines
451 #: 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] = []456457 #: 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] = []464465 #: A list of shell context processor functions that should be run466 #: when a shell context is created.467 #:
664 unmodified lines
11321133 @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 lines
1145 :param name: the optional name of the filter, otherwise the1146 function name will be used.1147 """11481155 def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:1149 def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable:1150 self.add_template_filter(f, name=name)1151 return f11521153 return decorator11541155 @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 lines
11661167 @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 lines
1186 :param name: the optional name of the test, otherwise the1187 function name will be used.1188 """11891196 def decorator(f: TemplateTestCallable) -> TemplateTestCallable:1190 def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable:1191 self.add_template_test(f, name=name)1192 return f11931194 return decorator11951196 @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 lines
12091210 @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 lines
1224 :param name: the optional name of the global function, otherwise the1225 function name will be used.1226 """12271234 def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:1228 def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable:1229 self.add_template_global(f, name=name)1230 return f12311232 return decorator12331234 @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 lines
1246 self.jinja_env.globals[name or f.__name__] = f12471248 @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.12541255 The function will be called without any arguments and its return
4 unmodified lines
1260 self.before_first_request_funcs.append(f)1261 return f12621263 @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 lines
1301 """1302 self.shell_context_processors.append(f)1303 return f13041311 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 lines
1326 return None13271328 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 lines
1396 return False13971398 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 either
61 unmodified lines
14661467 raise e14681469 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)14731474 if handler is not None:
45 unmodified lines
1520 from .debughelpers import FormDataRoutingRedirect15211522 raise FormDataRoutingRedirect(request)15231530 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 lines
1563 return self.finalize_request(rv)15641565 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 the
232 unmodified lines
1804 Moved from ``flask.redirect``, which calls this method.1805 """1806 return _wz_redirect(location, code=code, Response=self.response_class)18071814 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`.18111812 :param rv: the return value from the view function. The view function
83 unmodified lines
1896 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 lines
2025 raise20262027 raise error20282033 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 lines
modified:src/flask/blueprints.py+23 added-31 removed
1 unmodified line
2import typing as t3from collections import defaultdict4from functools import update_wrapper56from . import typing as ft7from .scaffold import _endpoint_from_view_func8from .scaffold import _sentinel9from .scaffold import Scaffold10from .scaffold import setupmethod10from .typing import AfterRequestCallable11from .typing import BeforeFirstRequestCallable12from .typing import BeforeRequestCallable13from .typing import TeardownCallable14from .typing import TemplateContextProcessorCallable15from .typing import TemplateFilterCallable16from .typing import TemplateGlobalCallable17from .typing import TemplateTestCallable18from .typing import URLDefaultCallable19from .typing import URLValuePreprocessorCallable1112if t.TYPE_CHECKING: # pragma: no cover13 from .app import Flask23 from .typing import ErrorHandlerCallable1415DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]1617
399 unmodified lines
417418 @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.424425 :param name: the optional name of the filter, otherwise the426 function name will be used.427 """428439 def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:429 def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable:430 self.add_app_template_filter(f, name=name)431 return f432433 return decorator434435 @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 lines
451452 @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.458459 .. versionadded:: 0.10
1 unmodified line
461 :param name: the optional name of the test, otherwise the462 function name will be used.463 """464475 def decorator(f: TemplateTestCallable) -> TemplateTestCallable:465 def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable:466 self.add_app_template_test(f, name=name)467 return f468469 return decorator470471 @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 lines
489490 @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.496497 .. versionadded:: 0.10
1 unmodified line
499 :param name: the optional name of the global, otherwise the500 function name will be used.501 """502513 def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:503 def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable:504 self.add_app_template_global(f, name=name)505 return f506507 return decorator508509 @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 lines
525526 self.record_once(register_template)527528 @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 lines
538 return f539540 @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 f549558 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 line
556 )557 return f558559 @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 lines
568 return f569570 @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 lines
584 """Like :meth:`Flask.errorhandler` but for a blueprint. This585 handler is used for all requests, even if outside of the blueprint.586 """587596 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 f591592 return decorator593594 @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 f603604 @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 line
modified:src/flask/ctx.py+3 added-3 removed
3 unmodified lines
4from types import TracebackType56from werkzeug.exceptions import HTTPException78from . import typing as ft9from .globals import _app_ctx_stack10from .globals import _request_ctx_stack11from .signals import appcontext_popped12from .signals import appcontext_pushed12from .typing import AfterRequestCallable1314if t.TYPE_CHECKING: # pragma: no cover15 from .app import Flask16 from .sessions import SessionMixin
91 unmodified lines
108 return f"<flask.g of {top.app.name!r}>"109 return object.__repr__(self)110111112def after_this_request(f: AfterRequestCallable) -> AfterRequestCallable:112def 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 lines
340341 # 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] = []345346 @property347 def g(self) -> _AppCtxGlobals:348 import warnings
165 unmodified lines
modified:src/flask/scaffold.py+21 added-28 removed
10 unmodified lines
11from jinja2 import FileSystemLoader12from werkzeug.exceptions import default_exceptions13from werkzeug.exceptions import HTTPException1415from . import typing as ft16from .cli import AppGroup17from .globals import current_app18from .helpers import get_root_path19from .helpers import locked_cached_property20from .helpers import send_from_directory21from .templating import _default_template_ctx_processor21from .typing import AfterRequestCallable22from .typing import AppOrBlueprintKey23from .typing import BeforeRequestCallable24from .typing import TeardownCallable25from .typing import TemplateContextProcessorCallable26from .typing import URLDefaultCallable27from .typing import URLValuePreprocessorCallable2223if t.TYPE_CHECKING: # pragma: no cover30 from .typing import ErrorHandlerCallable24 from .wrappers import Response2526# a singleton sentinel value for parameter defaults27_sentinel = object()
95 unmodified lines
123 #: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))130131 #: A data structure of functions to call at the beginning of132 #: each request, in the format ``{scope: [functions]}``. The
5 unmodified lines
138 #: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)144145 #: A data structure of functions to call at the end of each146 #: request, in the format ``{scope: [functions]}``. The
5 unmodified lines
152 #: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)158159 #: A data structure of functions to call at the end of each160 #: request even if an exception is raised, in the format
6 unmodified lines
167 #: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)173174 #: A data structure of functions to call to pass extra context175 #: values when rendering templates, in the format
6 unmodified lines
182 #: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]})188189 #: A data structure of functions to call to modify the keyword190 #: arguments passed to the view function, in the format
6 unmodified lines
197 #: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)204205 #: A data structure of functions to call to modify the keyword206 #: arguments when generating URLs, in the format
6 unmodified lines
213 #: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)219220 def __repr__(self) -> str:221 return f"<{type(self).__name__} {self.name!r}>"
299 unmodified lines
521522 return decorator523524 @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.527528 For example, this can be used to open a database connection, or529 to load the logged in user from the session.
13 unmodified lines
543 self.before_request_funcs.setdefault(None, []).append(f)544 return f545546 @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.549550 The function is called with the response object, and must return551 a response object. This allows the functions to modify or
7 unmodified lines
559 self.after_request_funcs.setdefault(None, []).append(f)560 return f561562 @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 lines
599 return f600601 @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 f608609 @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 lines
625 self.url_value_preprocessors[None].append(f)626 return f627628 @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 lines
636637 @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.642643 A decorator that is used to register a function given an644 error code. Example::
21 unmodified lines
666 :param code_or_exception: the code as integer for the handler, or667 an arbitrary exception668 """669677 def decorator(f: "ErrorHandlerCallable") -> "ErrorHandlerCallable":670 def decorator(f: ft.ErrorHandlerCallable) -> ft.ErrorHandlerCallable:671 self.register_error_handler(code_or_exception, f)672 return f673674 return decorator
1 unmodified line
676 @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 lines
modified:src/flask/typing.py+7 added-2 removed
2 unmodified lines
34if 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: F40189# The possible types that are directly convertible or are a Response object.10ResponseValue = t.Union[11 "Response",
22 unmodified lines
34 t.Tuple[ResponseValue, StatusCode, HeadersValue],35 "WSGIApplication",36]3738# 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.41ResponseClass = t.TypeVar("ResponseClass", bound="Response")4243AppOrBlueprintKey = t.Optional[str] # The App key is None, whereas blueprints are named39AfterRequestCallable = t.Callable[["Response"], "Response"]44AfterRequestCallable = t.Callable[[ResponseClass], ResponseClass]45BeforeFirstRequestCallable = t.Callable[[], None]46BeforeRequestCallable = t.Callable[[], t.Optional[ResponseReturnValue]]47TeardownCallable = t.Callable[[t.Optional[BaseException]], None]48TemplateContextProcessorCallable = t.Callable[[], t.Dict[str, t.Any]]
12 unmodified lines
modified:src/flask/views.py+4 added-4 removed
1import typing as t23from . import typing as ft4from .globals import current_app5from .globals import request5from .typing import ResponseReturnValue678http_method_funcs = frozenset(9 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]
48 unmodified lines
58 #:59 #: .. versionadded:: 0.860 decorators: t.List[t.Callable] = []6162 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 lines
78 The arguments passed to :meth:`as_view` are forwarded to the79 constructor of the class.80 """8182 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)8586 if cls.decorators:
58 unmodified lines
145146 app.add_url_rule('/counter', view_func=CounterAPI.as_view('counter'))147 """148149 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)151152 # If the request method is HEAD and we don't have a handler for it153 # retry with GET.
5 unmodified lines
modified:CHANGES.rst+10 added
20 unmodified lines
21 this will become an error just like the application setup methods.22 :issue:`4571`232425Version 2.1.326-------------2728Unreleased2930- Inline some optional imports that are only used for certain CLI31 commands. :pr:`4606`32- Relax type annotation for ``after_request`` functions. :issue:`4600`333435Version 2.1.236-------------3738Released 2022-04-28
1278 unmodified lines