blueprints.py 23 KB

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