blueprints.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706
  1. import json
  2. import os
  3. import typing as t
  4. from collections import defaultdict
  5. from functools import update_wrapper
  6. from . import typing as ft
  7. from .scaffold import _endpoint_from_view_func
  8. from .scaffold import _sentinel
  9. from .scaffold import Scaffold
  10. from .scaffold import setupmethod
  11. if t.TYPE_CHECKING: # pragma: no cover
  12. from .app import Flask
  13. DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]
  14. T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)
  15. T_before_first_request = t.TypeVar(
  16. "T_before_first_request", bound=ft.BeforeFirstRequestCallable
  17. )
  18. T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)
  19. T_error_handler = t.TypeVar("T_error_handler", bound=ft.ErrorHandlerCallable)
  20. T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
  21. T_template_context_processor = t.TypeVar(
  22. "T_template_context_processor", bound=ft.TemplateContextProcessorCallable
  23. )
  24. T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
  25. T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
  26. T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)
  27. T_url_defaults = t.TypeVar("T_url_defaults", bound=ft.URLDefaultCallable)
  28. T_url_value_preprocessor = t.TypeVar(
  29. "T_url_value_preprocessor", bound=ft.URLValuePreprocessorCallable
  30. )
  31. class BlueprintSetupState:
  32. """Temporary holder object for registering a blueprint with the
  33. application. An instance of this class is created by the
  34. :meth:`~flask.Blueprint.make_setup_state` method and later passed
  35. to all register callback functions.
  36. """
  37. def __init__(
  38. self,
  39. blueprint: "Blueprint",
  40. app: "Flask",
  41. options: t.Any,
  42. first_registration: bool,
  43. ) -> None:
  44. #: a reference to the current application
  45. self.app = app
  46. #: a reference to the blueprint that created this setup state.
  47. self.blueprint = blueprint
  48. #: a dictionary with all options that were passed to the
  49. #: :meth:`~flask.Flask.register_blueprint` method.
  50. self.options = options
  51. #: as blueprints can be registered multiple times with the
  52. #: application and not everything wants to be registered
  53. #: multiple times on it, this attribute can be used to figure
  54. #: out if the blueprint was registered in the past already.
  55. self.first_registration = first_registration
  56. subdomain = self.options.get("subdomain")
  57. if subdomain is None:
  58. subdomain = self.blueprint.subdomain
  59. #: The subdomain that the blueprint should be active for, ``None``
  60. #: otherwise.
  61. self.subdomain = subdomain
  62. url_prefix = self.options.get("url_prefix")
  63. if url_prefix is None:
  64. url_prefix = self.blueprint.url_prefix
  65. #: The prefix that should be used for all URLs defined on the
  66. #: blueprint.
  67. self.url_prefix = url_prefix
  68. self.name = self.options.get("name", blueprint.name)
  69. self.name_prefix = self.options.get("name_prefix", "")
  70. #: A dictionary with URL defaults that is added to each and every
  71. #: URL that was defined with the blueprint.
  72. self.url_defaults = dict(self.blueprint.url_values_defaults)
  73. self.url_defaults.update(self.options.get("url_defaults", ()))
  74. def add_url_rule(
  75. self,
  76. rule: str,
  77. endpoint: t.Optional[str] = None,
  78. view_func: t.Optional[t.Callable] = None,
  79. **options: t.Any,
  80. ) -> None:
  81. """A helper method to register a rule (and optionally a view function)
  82. to the application. The endpoint is automatically prefixed with the
  83. blueprint's name.
  84. """
  85. if self.url_prefix is not None:
  86. if rule:
  87. rule = "/".join((self.url_prefix.rstrip("/"), rule.lstrip("/")))
  88. else:
  89. rule = self.url_prefix
  90. options.setdefault("subdomain", self.subdomain)
  91. if endpoint is None:
  92. endpoint = _endpoint_from_view_func(view_func) # type: ignore
  93. defaults = self.url_defaults
  94. if "defaults" in options:
  95. defaults = dict(defaults, **options.pop("defaults"))
  96. self.app.add_url_rule(
  97. rule,
  98. f"{self.name_prefix}.{self.name}.{endpoint}".lstrip("."),
  99. view_func,
  100. defaults=defaults,
  101. **options,
  102. )
  103. class Blueprint(Scaffold):
  104. """Represents a blueprint, a collection of routes and other
  105. app-related functions that can be registered on a real application
  106. later.
  107. A blueprint is an object that allows defining application functions
  108. without requiring an application object ahead of time. It uses the
  109. same decorators as :class:`~flask.Flask`, but defers the need for an
  110. application by recording them for later registration.
  111. Decorating a function with a blueprint creates a deferred function
  112. that is called with :class:`~flask.blueprints.BlueprintSetupState`
  113. when the blueprint is registered on an application.
  114. See :doc:`/blueprints` for more information.
  115. :param name: The name of the blueprint. Will be prepended to each
  116. endpoint name.
  117. :param import_name: The name of the blueprint package, usually
  118. ``__name__``. This helps locate the ``root_path`` for the
  119. blueprint.
  120. :param static_folder: A folder with static files that should be
  121. served by the blueprint's static route. The path is relative to
  122. the blueprint's root path. Blueprint static files are disabled
  123. by default.
  124. :param static_url_path: The url to serve static files from.
  125. Defaults to ``static_folder``. If the blueprint does not have
  126. a ``url_prefix``, the app's static route will take precedence,
  127. and the blueprint's static files won't be accessible.
  128. :param template_folder: A folder with templates that should be added
  129. to the app's template search path. The path is relative to the
  130. blueprint's root path. Blueprint templates are disabled by
  131. default. Blueprint templates have a lower precedence than those
  132. in the app's templates folder.
  133. :param url_prefix: A path to prepend to all of the blueprint's URLs,
  134. to make them distinct from the rest of the app's routes.
  135. :param subdomain: A subdomain that blueprint routes will match on by
  136. default.
  137. :param url_defaults: A dict of default values that blueprint routes
  138. will receive by default.
  139. :param root_path: By default, the blueprint will automatically set
  140. this based on ``import_name``. In certain situations this
  141. automatic detection can fail, so the path can be specified
  142. manually instead.
  143. .. versionchanged:: 1.1.0
  144. Blueprints have a ``cli`` group to register nested CLI commands.
  145. The ``cli_group`` parameter controls the name of the group under
  146. the ``flask`` command.
  147. .. versionadded:: 0.7
  148. """
  149. _got_registered_once = False
  150. _json_encoder: t.Union[t.Type[json.JSONEncoder], None] = None
  151. _json_decoder: t.Union[t.Type[json.JSONDecoder], None] = None
  152. @property # type: ignore[override]
  153. def json_encoder( # type: ignore[override]
  154. self,
  155. ) -> t.Union[t.Type[json.JSONEncoder], None]:
  156. """Blueprint-local JSON encoder class to use. Set to ``None`` to use the app's.
  157. .. deprecated:: 2.2
  158. Will be removed in Flask 2.3. Customize
  159. :attr:`json_provider_class` instead.
  160. .. versionadded:: 0.10
  161. """
  162. import warnings
  163. warnings.warn(
  164. "'bp.json_encoder' is deprecated and will be removed in Flask 2.3."
  165. " Customize 'app.json_provider_class' or 'app.json' instead.",
  166. DeprecationWarning,
  167. stacklevel=2,
  168. )
  169. return self._json_encoder
  170. @json_encoder.setter
  171. def json_encoder(self, value: t.Union[t.Type[json.JSONEncoder], None]) -> None:
  172. import warnings
  173. warnings.warn(
  174. "'bp.json_encoder' is deprecated and will be removed in Flask 2.3."
  175. " Customize 'app.json_provider_class' or 'app.json' instead.",
  176. DeprecationWarning,
  177. stacklevel=2,
  178. )
  179. self._json_encoder = value
  180. @property # type: ignore[override]
  181. def json_decoder( # type: ignore[override]
  182. self,
  183. ) -> t.Union[t.Type[json.JSONDecoder], None]:
  184. """Blueprint-local JSON decoder class to use. Set to ``None`` to use the app's.
  185. .. deprecated:: 2.2
  186. Will be removed in Flask 2.3. Customize
  187. :attr:`json_provider_class` instead.
  188. .. versionadded:: 0.10
  189. """
  190. import warnings
  191. warnings.warn(
  192. "'bp.json_decoder' is deprecated and will be removed in Flask 2.3."
  193. " Customize 'app.json_provider_class' or 'app.json' instead.",
  194. DeprecationWarning,
  195. stacklevel=2,
  196. )
  197. return self._json_decoder
  198. @json_decoder.setter
  199. def json_decoder(self, value: t.Union[t.Type[json.JSONDecoder], None]) -> None:
  200. import warnings
  201. warnings.warn(
  202. "'bp.json_decoder' is deprecated and will be removed in Flask 2.3."
  203. " Customize 'app.json_provider_class' or 'app.json' instead.",
  204. DeprecationWarning,
  205. stacklevel=2,
  206. )
  207. self._json_decoder = value
  208. def __init__(
  209. self,
  210. name: str,
  211. import_name: str,
  212. static_folder: t.Optional[t.Union[str, os.PathLike]] = None,
  213. static_url_path: t.Optional[str] = None,
  214. template_folder: t.Optional[str] = None,
  215. url_prefix: t.Optional[str] = None,
  216. subdomain: t.Optional[str] = None,
  217. url_defaults: t.Optional[dict] = None,
  218. root_path: t.Optional[str] = None,
  219. cli_group: t.Optional[str] = _sentinel, # type: ignore
  220. ):
  221. super().__init__(
  222. import_name=import_name,
  223. static_folder=static_folder,
  224. static_url_path=static_url_path,
  225. template_folder=template_folder,
  226. root_path=root_path,
  227. )
  228. if "." in name:
  229. raise ValueError("'name' may not contain a dot '.' character.")
  230. self.name = name
  231. self.url_prefix = url_prefix
  232. self.subdomain = subdomain
  233. self.deferred_functions: t.List[DeferredSetupFunction] = []
  234. if url_defaults is None:
  235. url_defaults = {}
  236. self.url_values_defaults = url_defaults
  237. self.cli_group = cli_group
  238. self._blueprints: t.List[t.Tuple["Blueprint", dict]] = []
  239. def _check_setup_finished(self, f_name: str) -> None:
  240. if self._got_registered_once:
  241. import warnings
  242. warnings.warn(
  243. f"The setup method '{f_name}' can no longer be called on"
  244. f" the blueprint '{self.name}'. It has already been"
  245. " registered at least once, any changes will not be"
  246. " applied consistently.\n"
  247. "Make sure all imports, decorators, functions, etc."
  248. " needed to set up the blueprint are done before"
  249. " registering it.\n"
  250. "This warning will become an exception in Flask 2.3.",
  251. UserWarning,
  252. stacklevel=3,
  253. )
  254. @setupmethod
  255. def record(self, func: t.Callable) -> None:
  256. """Registers a function that is called when the blueprint is
  257. registered on the application. This function is called with the
  258. state as argument as returned by the :meth:`make_setup_state`
  259. method.
  260. """
  261. self.deferred_functions.append(func)
  262. @setupmethod
  263. def record_once(self, func: t.Callable) -> None:
  264. """Works like :meth:`record` but wraps the function in another
  265. function that will ensure the function is only called once. If the
  266. blueprint is registered a second time on the application, the
  267. function passed is not called.
  268. """
  269. def wrapper(state: BlueprintSetupState) -> None:
  270. if state.first_registration:
  271. func(state)
  272. self.record(update_wrapper(wrapper, func))
  273. def make_setup_state(
  274. self, app: "Flask", options: dict, first_registration: bool = False
  275. ) -> BlueprintSetupState:
  276. """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`
  277. object that is later passed to the register callback functions.
  278. Subclasses can override this to return a subclass of the setup state.
  279. """
  280. return BlueprintSetupState(self, app, options, first_registration)
  281. @setupmethod
  282. def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:
  283. """Register a :class:`~flask.Blueprint` on this blueprint. Keyword
  284. arguments passed to this method will override the defaults set
  285. on the blueprint.
  286. .. versionchanged:: 2.0.1
  287. The ``name`` option can be used to change the (pre-dotted)
  288. name the blueprint is registered with. This allows the same
  289. blueprint to be registered multiple times with unique names
  290. for ``url_for``.
  291. .. versionadded:: 2.0
  292. """
  293. if blueprint is self:
  294. raise ValueError("Cannot register a blueprint on itself")
  295. self._blueprints.append((blueprint, options))
  296. def register(self, app: "Flask", options: dict) -> None:
  297. """Called by :meth:`Flask.register_blueprint` to register all
  298. views and callbacks registered on the blueprint with the
  299. application. Creates a :class:`.BlueprintSetupState` and calls
  300. each :meth:`record` callback with it.
  301. :param app: The application this blueprint is being registered
  302. with.
  303. :param options: Keyword arguments forwarded from
  304. :meth:`~Flask.register_blueprint`.
  305. .. versionchanged:: 2.0.1
  306. Nested blueprints are registered with their dotted name.
  307. This allows different blueprints with the same name to be
  308. nested at different locations.
  309. .. versionchanged:: 2.0.1
  310. The ``name`` option can be used to change the (pre-dotted)
  311. name the blueprint is registered with. This allows the same
  312. blueprint to be registered multiple times with unique names
  313. for ``url_for``.
  314. .. versionchanged:: 2.0.1
  315. Registering the same blueprint with the same name multiple
  316. times is deprecated and will become an error in Flask 2.1.
  317. """
  318. name_prefix = options.get("name_prefix", "")
  319. self_name = options.get("name", self.name)
  320. name = f"{name_prefix}.{self_name}".lstrip(".")
  321. if name in app.blueprints:
  322. bp_desc = "this" if app.blueprints[name] is self else "a different"
  323. existing_at = f" '{name}'" if self_name != name else ""
  324. raise ValueError(
  325. f"The name '{self_name}' is already registered for"
  326. f" {bp_desc} blueprint{existing_at}. Use 'name=' to"
  327. f" provide a unique name."
  328. )
  329. first_bp_registration = not any(bp is self for bp in app.blueprints.values())
  330. first_name_registration = name not in app.blueprints
  331. app.blueprints[name] = self
  332. self._got_registered_once = True
  333. state = self.make_setup_state(app, options, first_bp_registration)
  334. if self.has_static_folder:
  335. state.add_url_rule(
  336. f"{self.static_url_path}/<path:filename>",
  337. view_func=self.send_static_file,
  338. endpoint="static",
  339. )
  340. # Merge blueprint data into parent.
  341. if first_bp_registration or first_name_registration:
  342. def extend(bp_dict, parent_dict):
  343. for key, values in bp_dict.items():
  344. key = name if key is None else f"{name}.{key}"
  345. parent_dict[key].extend(values)
  346. for key, value in self.error_handler_spec.items():
  347. key = name if key is None else f"{name}.{key}"
  348. value = defaultdict(
  349. dict,
  350. {
  351. code: {
  352. exc_class: func for exc_class, func in code_values.items()
  353. }
  354. for code, code_values in value.items()
  355. },
  356. )
  357. app.error_handler_spec[key] = value
  358. for endpoint, func in self.view_functions.items():
  359. app.view_functions[endpoint] = func
  360. extend(self.before_request_funcs, app.before_request_funcs)
  361. extend(self.after_request_funcs, app.after_request_funcs)
  362. extend(
  363. self.teardown_request_funcs,
  364. app.teardown_request_funcs,
  365. )
  366. extend(self.url_default_functions, app.url_default_functions)
  367. extend(self.url_value_preprocessors, app.url_value_preprocessors)
  368. extend(self.template_context_processors, app.template_context_processors)
  369. for deferred in self.deferred_functions:
  370. deferred(state)
  371. cli_resolved_group = options.get("cli_group", self.cli_group)
  372. if self.cli.commands:
  373. if cli_resolved_group is None:
  374. app.cli.commands.update(self.cli.commands)
  375. elif cli_resolved_group is _sentinel:
  376. self.cli.name = name
  377. app.cli.add_command(self.cli)
  378. else:
  379. self.cli.name = cli_resolved_group
  380. app.cli.add_command(self.cli)
  381. for blueprint, bp_options in self._blueprints:
  382. bp_options = bp_options.copy()
  383. bp_url_prefix = bp_options.get("url_prefix")
  384. if bp_url_prefix is None:
  385. bp_url_prefix = blueprint.url_prefix
  386. if state.url_prefix is not None and bp_url_prefix is not None:
  387. bp_options["url_prefix"] = (
  388. state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/")
  389. )
  390. elif bp_url_prefix is not None:
  391. bp_options["url_prefix"] = bp_url_prefix
  392. elif state.url_prefix is not None:
  393. bp_options["url_prefix"] = state.url_prefix
  394. bp_options["name_prefix"] = name
  395. blueprint.register(app, bp_options)
  396. @setupmethod
  397. def add_url_rule(
  398. self,
  399. rule: str,
  400. endpoint: t.Optional[str] = None,
  401. view_func: t.Optional[ft.RouteCallable] = None,
  402. provide_automatic_options: t.Optional[bool] = None,
  403. **options: t.Any,
  404. ) -> None:
  405. """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for
  406. the :func:`url_for` function is prefixed with the name of the blueprint.
  407. """
  408. if endpoint and "." in endpoint:
  409. raise ValueError("'endpoint' may not contain a dot '.' character.")
  410. if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__:
  411. raise ValueError("'view_func' name may not contain a dot '.' character.")
  412. self.record(
  413. lambda s: s.add_url_rule(
  414. rule,
  415. endpoint,
  416. view_func,
  417. provide_automatic_options=provide_automatic_options,
  418. **options,
  419. )
  420. )
  421. @setupmethod
  422. def app_template_filter(
  423. self, name: t.Optional[str] = None
  424. ) -> t.Callable[[T_template_filter], T_template_filter]:
  425. """Register a custom template filter, available application wide. Like
  426. :meth:`Flask.template_filter` but for a blueprint.
  427. :param name: the optional name of the filter, otherwise the
  428. function name will be used.
  429. """
  430. def decorator(f: T_template_filter) -> T_template_filter:
  431. self.add_app_template_filter(f, name=name)
  432. return f
  433. return decorator
  434. @setupmethod
  435. def add_app_template_filter(
  436. self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None
  437. ) -> None:
  438. """Register a custom template filter, available application wide. Like
  439. :meth:`Flask.add_template_filter` but for a blueprint. Works exactly
  440. like the :meth:`app_template_filter` decorator.
  441. :param name: the optional name of the filter, otherwise the
  442. function name will be used.
  443. """
  444. def register_template(state: BlueprintSetupState) -> None:
  445. state.app.jinja_env.filters[name or f.__name__] = f
  446. self.record_once(register_template)
  447. @setupmethod
  448. def app_template_test(
  449. self, name: t.Optional[str] = None
  450. ) -> t.Callable[[T_template_test], T_template_test]:
  451. """Register a custom template test, available application wide. Like
  452. :meth:`Flask.template_test` but for a blueprint.
  453. .. versionadded:: 0.10
  454. :param name: the optional name of the test, otherwise the
  455. function name will be used.
  456. """
  457. def decorator(f: T_template_test) -> T_template_test:
  458. self.add_app_template_test(f, name=name)
  459. return f
  460. return decorator
  461. @setupmethod
  462. def add_app_template_test(
  463. self, f: ft.TemplateTestCallable, name: t.Optional[str] = None
  464. ) -> None:
  465. """Register a custom template test, available application wide. Like
  466. :meth:`Flask.add_template_test` but for a blueprint. Works exactly
  467. like the :meth:`app_template_test` decorator.
  468. .. versionadded:: 0.10
  469. :param name: the optional name of the test, otherwise the
  470. function name will be used.
  471. """
  472. def register_template(state: BlueprintSetupState) -> None:
  473. state.app.jinja_env.tests[name or f.__name__] = f
  474. self.record_once(register_template)
  475. @setupmethod
  476. def app_template_global(
  477. self, name: t.Optional[str] = None
  478. ) -> t.Callable[[T_template_global], T_template_global]:
  479. """Register a custom template global, available application wide. Like
  480. :meth:`Flask.template_global` but for a blueprint.
  481. .. versionadded:: 0.10
  482. :param name: the optional name of the global, otherwise the
  483. function name will be used.
  484. """
  485. def decorator(f: T_template_global) -> T_template_global:
  486. self.add_app_template_global(f, name=name)
  487. return f
  488. return decorator
  489. @setupmethod
  490. def add_app_template_global(
  491. self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None
  492. ) -> None:
  493. """Register a custom template global, available application wide. Like
  494. :meth:`Flask.add_template_global` but for a blueprint. Works exactly
  495. like the :meth:`app_template_global` decorator.
  496. .. versionadded:: 0.10
  497. :param name: the optional name of the global, otherwise the
  498. function name will be used.
  499. """
  500. def register_template(state: BlueprintSetupState) -> None:
  501. state.app.jinja_env.globals[name or f.__name__] = f
  502. self.record_once(register_template)
  503. @setupmethod
  504. def before_app_request(self, f: T_before_request) -> T_before_request:
  505. """Like :meth:`Flask.before_request`. Such a function is executed
  506. before each request, even if outside of a blueprint.
  507. """
  508. self.record_once(
  509. lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)
  510. )
  511. return f
  512. @setupmethod
  513. def before_app_first_request(
  514. self, f: T_before_first_request
  515. ) -> T_before_first_request:
  516. """Like :meth:`Flask.before_first_request`. Such a function is
  517. executed before the first request to the application.
  518. .. deprecated:: 2.2
  519. Will be removed in Flask 2.3. Run setup code when creating
  520. the application instead.
  521. """
  522. import warnings
  523. warnings.warn(
  524. "'before_app_first_request' is deprecated and will be"
  525. " removed in Flask 2.3. Use 'record_once' instead to run"
  526. " setup code when registering the blueprint.",
  527. DeprecationWarning,
  528. stacklevel=2,
  529. )
  530. self.record_once(lambda s: s.app.before_first_request_funcs.append(f))
  531. return f
  532. @setupmethod
  533. def after_app_request(self, f: T_after_request) -> T_after_request:
  534. """Like :meth:`Flask.after_request` but for a blueprint. Such a function
  535. is executed after each request, even if outside of the blueprint.
  536. """
  537. self.record_once(
  538. lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)
  539. )
  540. return f
  541. @setupmethod
  542. def teardown_app_request(self, f: T_teardown) -> T_teardown:
  543. """Like :meth:`Flask.teardown_request` but for a blueprint. Such a
  544. function is executed when tearing down each request, even if outside of
  545. the blueprint.
  546. """
  547. self.record_once(
  548. lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)
  549. )
  550. return f
  551. @setupmethod
  552. def app_context_processor(
  553. self, f: T_template_context_processor
  554. ) -> T_template_context_processor:
  555. """Like :meth:`Flask.context_processor` but for a blueprint. Such a
  556. function is executed each request, even if outside of the blueprint.
  557. """
  558. self.record_once(
  559. lambda s: s.app.template_context_processors.setdefault(None, []).append(f)
  560. )
  561. return f
  562. @setupmethod
  563. def app_errorhandler(
  564. self, code: t.Union[t.Type[Exception], int]
  565. ) -> t.Callable[[T_error_handler], T_error_handler]:
  566. """Like :meth:`Flask.errorhandler` but for a blueprint. This
  567. handler is used for all requests, even if outside of the blueprint.
  568. """
  569. def decorator(f: T_error_handler) -> T_error_handler:
  570. self.record_once(lambda s: s.app.errorhandler(code)(f))
  571. return f
  572. return decorator
  573. @setupmethod
  574. def app_url_value_preprocessor(
  575. self, f: T_url_value_preprocessor
  576. ) -> T_url_value_preprocessor:
  577. """Same as :meth:`url_value_preprocessor` but application wide."""
  578. self.record_once(
  579. lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)
  580. )
  581. return f
  582. @setupmethod
  583. def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:
  584. """Same as :meth:`url_defaults` but application wide."""
  585. self.record_once(
  586. lambda s: s.app.url_default_functions.setdefault(None, []).append(f)
  587. )
  588. return f