blueprints.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712
  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
  153. def json_encoder(
  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
  181. def json_decoder(
  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[t.Union[str, os.PathLike]] = 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. """Register a URL rule with the blueprint. See :meth:`.Flask.add_url_rule` for
  406. full documentation.
  407. The URL rule is prefixed with the blueprint's URL prefix. The endpoint name,
  408. used with :func:`url_for`, is prefixed with the blueprint's name.
  409. """
  410. if endpoint and "." in endpoint:
  411. raise ValueError("'endpoint' may not contain a dot '.' character.")
  412. if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__:
  413. raise ValueError("'view_func' name may not contain a dot '.' character.")
  414. self.record(
  415. lambda s: s.add_url_rule(
  416. rule,
  417. endpoint,
  418. view_func,
  419. provide_automatic_options=provide_automatic_options,
  420. **options,
  421. )
  422. )
  423. @setupmethod
  424. def app_template_filter(
  425. self, name: t.Optional[str] = None
  426. ) -> t.Callable[[T_template_filter], T_template_filter]:
  427. """Register a template filter, available in any template rendered by the
  428. application. Equivalent to :meth:`.Flask.template_filter`.
  429. :param name: the optional name of the filter, otherwise the
  430. function name will be used.
  431. """
  432. def decorator(f: T_template_filter) -> T_template_filter:
  433. self.add_app_template_filter(f, name=name)
  434. return f
  435. return decorator
  436. @setupmethod
  437. def add_app_template_filter(
  438. self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None
  439. ) -> None:
  440. """Register a template filter, available in any template rendered by the
  441. application. Works like the :meth:`app_template_filter` decorator. Equivalent to
  442. :meth:`.Flask.add_template_filter`.
  443. :param name: the optional name of the filter, otherwise the
  444. function name will be used.
  445. """
  446. def register_template(state: BlueprintSetupState) -> None:
  447. state.app.jinja_env.filters[name or f.__name__] = f
  448. self.record_once(register_template)
  449. @setupmethod
  450. def app_template_test(
  451. self, name: t.Optional[str] = None
  452. ) -> t.Callable[[T_template_test], T_template_test]:
  453. """Register a template test, available in any template rendered by the
  454. application. Equivalent to :meth:`.Flask.template_test`.
  455. .. versionadded:: 0.10
  456. :param name: the optional name of the test, otherwise the
  457. function name will be used.
  458. """
  459. def decorator(f: T_template_test) -> T_template_test:
  460. self.add_app_template_test(f, name=name)
  461. return f
  462. return decorator
  463. @setupmethod
  464. def add_app_template_test(
  465. self, f: ft.TemplateTestCallable, name: t.Optional[str] = None
  466. ) -> None:
  467. """Register a template test, available in any template rendered by the
  468. application. Works like the :meth:`app_template_test` decorator. Equivalent to
  469. :meth:`.Flask.add_template_test`.
  470. .. versionadded:: 0.10
  471. :param name: the optional name of the test, otherwise the
  472. function name will be used.
  473. """
  474. def register_template(state: BlueprintSetupState) -> None:
  475. state.app.jinja_env.tests[name or f.__name__] = f
  476. self.record_once(register_template)
  477. @setupmethod
  478. def app_template_global(
  479. self, name: t.Optional[str] = None
  480. ) -> t.Callable[[T_template_global], T_template_global]:
  481. """Register a template global, available in any template rendered by the
  482. application. Equivalent to :meth:`.Flask.template_global`.
  483. .. versionadded:: 0.10
  484. :param name: the optional name of the global, otherwise the
  485. function name will be used.
  486. """
  487. def decorator(f: T_template_global) -> T_template_global:
  488. self.add_app_template_global(f, name=name)
  489. return f
  490. return decorator
  491. @setupmethod
  492. def add_app_template_global(
  493. self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None
  494. ) -> None:
  495. """Register a template global, available in any template rendered by the
  496. application. Works like the :meth:`app_template_global` decorator. Equivalent to
  497. :meth:`.Flask.add_template_global`.
  498. .. versionadded:: 0.10
  499. :param name: the optional name of the global, otherwise the
  500. function name will be used.
  501. """
  502. def register_template(state: BlueprintSetupState) -> None:
  503. state.app.jinja_env.globals[name or f.__name__] = f
  504. self.record_once(register_template)
  505. @setupmethod
  506. def before_app_request(self, f: T_before_request) -> T_before_request:
  507. """Like :meth:`before_request`, but before every request, not only those handled
  508. by the blueprint. Equivalent to :meth:`.Flask.before_request`.
  509. """
  510. self.record_once(
  511. lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)
  512. )
  513. return f
  514. @setupmethod
  515. def before_app_first_request(
  516. self, f: T_before_first_request
  517. ) -> T_before_first_request:
  518. """Register a function to run before the first request to the application is
  519. handled by the worker. Equivalent to :meth:`.Flask.before_first_request`.
  520. .. deprecated:: 2.2
  521. Will be removed in Flask 2.3. Run setup code when creating
  522. the application instead.
  523. """
  524. import warnings
  525. warnings.warn(
  526. "'before_app_first_request' is deprecated and will be"
  527. " removed in Flask 2.3. Use 'record_once' instead to run"
  528. " setup code when registering the blueprint.",
  529. DeprecationWarning,
  530. stacklevel=2,
  531. )
  532. self.record_once(lambda s: s.app.before_first_request_funcs.append(f))
  533. return f
  534. @setupmethod
  535. def after_app_request(self, f: T_after_request) -> T_after_request:
  536. """Like :meth:`after_request`, but after every request, not only those handled
  537. by the blueprint. Equivalent to :meth:`.Flask.after_request`.
  538. """
  539. self.record_once(
  540. lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)
  541. )
  542. return f
  543. @setupmethod
  544. def teardown_app_request(self, f: T_teardown) -> T_teardown:
  545. """Like :meth:`teardown_request`, but after every request, not only those
  546. handled by the blueprint. Equivalent to :meth:`.Flask.teardown_request`.
  547. """
  548. self.record_once(
  549. lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)
  550. )
  551. return f
  552. @setupmethod
  553. def app_context_processor(
  554. self, f: T_template_context_processor
  555. ) -> T_template_context_processor:
  556. """Like :meth:`context_processor`, but for templates rendered by every view, not
  557. only by the blueprint. Equivalent to :meth:`.Flask.context_processor`.
  558. """
  559. self.record_once(
  560. lambda s: s.app.template_context_processors.setdefault(None, []).append(f)
  561. )
  562. return f
  563. @setupmethod
  564. def app_errorhandler(
  565. self, code: t.Union[t.Type[Exception], int]
  566. ) -> t.Callable[[T_error_handler], T_error_handler]:
  567. """Like :meth:`errorhandler`, but for every request, not only those handled by
  568. the blueprint. Equivalent to :meth:`.Flask.errorhandler`.
  569. """
  570. def decorator(f: T_error_handler) -> T_error_handler:
  571. self.record_once(lambda s: s.app.errorhandler(code)(f))
  572. return f
  573. return decorator
  574. @setupmethod
  575. def app_url_value_preprocessor(
  576. self, f: T_url_value_preprocessor
  577. ) -> T_url_value_preprocessor:
  578. """Like :meth:`url_value_preprocessor`, but for every request, not only those
  579. handled by the blueprint. Equivalent to :meth:`.Flask.url_value_preprocessor`.
  580. """
  581. self.record_once(
  582. lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)
  583. )
  584. return f
  585. @setupmethod
  586. def app_url_defaults(self, f: T_url_defaults) -> T_url_defaults:
  587. """Like :meth:`url_defaults`, but for every request, not only those handled by
  588. the blueprint. Equivalent to :meth:`.Flask.url_defaults`.
  589. """
  590. self.record_once(
  591. lambda s: s.app.url_default_functions.setdefault(None, []).append(f)
  592. )
  593. return f