blueprints.py 23 KB

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