blueprints.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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. existing_at = f" '{name}'" if self_name != name else ""
  256. if app.blueprints[name] is not self:
  257. raise ValueError(
  258. f"The name '{self_name}' is already registered for"
  259. f" a different blueprint{existing_at}. Use 'name='"
  260. " to provide a unique name."
  261. )
  262. else:
  263. import warnings
  264. warnings.warn(
  265. f"The name '{self_name}' is already registered for"
  266. f" this blueprint{existing_at}. Use 'name=' to"
  267. " provide a unique name. This will become an error"
  268. " in Flask 2.1.",
  269. stacklevel=4,
  270. )
  271. first_bp_registration = not any(bp is self for bp in app.blueprints.values())
  272. first_name_registration = name not in app.blueprints
  273. app.blueprints[name] = self
  274. self._got_registered_once = True
  275. state = self.make_setup_state(app, options, first_bp_registration)
  276. if self.has_static_folder:
  277. state.add_url_rule(
  278. f"{self.static_url_path}/<path:filename>",
  279. view_func=self.send_static_file,
  280. endpoint="static",
  281. )
  282. # Merge blueprint data into parent.
  283. if first_bp_registration or first_name_registration:
  284. def extend(bp_dict, parent_dict):
  285. for key, values in bp_dict.items():
  286. key = name if key is None else f"{name}.{key}"
  287. parent_dict[key].extend(values)
  288. for key, value in self.error_handler_spec.items():
  289. key = name if key is None else f"{name}.{key}"
  290. value = defaultdict(
  291. dict,
  292. {
  293. code: {
  294. exc_class: func for exc_class, func in code_values.items()
  295. }
  296. for code, code_values in value.items()
  297. },
  298. )
  299. app.error_handler_spec[key] = value
  300. for endpoint, func in self.view_functions.items():
  301. app.view_functions[endpoint] = func
  302. extend(self.before_request_funcs, app.before_request_funcs)
  303. extend(self.after_request_funcs, app.after_request_funcs)
  304. extend(
  305. self.teardown_request_funcs,
  306. app.teardown_request_funcs,
  307. )
  308. extend(self.url_default_functions, app.url_default_functions)
  309. extend(self.url_value_preprocessors, app.url_value_preprocessors)
  310. extend(self.template_context_processors, app.template_context_processors)
  311. for deferred in self.deferred_functions:
  312. deferred(state)
  313. cli_resolved_group = options.get("cli_group", self.cli_group)
  314. if self.cli.commands:
  315. if cli_resolved_group is None:
  316. app.cli.commands.update(self.cli.commands)
  317. elif cli_resolved_group is _sentinel:
  318. self.cli.name = name
  319. app.cli.add_command(self.cli)
  320. else:
  321. self.cli.name = cli_resolved_group
  322. app.cli.add_command(self.cli)
  323. for blueprint, bp_options in self._blueprints:
  324. bp_options = bp_options.copy()
  325. bp_url_prefix = bp_options.get("url_prefix")
  326. if bp_url_prefix is None:
  327. bp_url_prefix = blueprint.url_prefix
  328. if state.url_prefix is not None and bp_url_prefix is not None:
  329. bp_options["url_prefix"] = (
  330. state.url_prefix.rstrip("/") + "/" + bp_url_prefix.lstrip("/")
  331. )
  332. elif bp_url_prefix is not None:
  333. bp_options["url_prefix"] = bp_url_prefix
  334. elif state.url_prefix is not None:
  335. bp_options["url_prefix"] = state.url_prefix
  336. bp_options["name_prefix"] = name
  337. blueprint.register(app, bp_options)
  338. def add_url_rule(
  339. self,
  340. rule: str,
  341. endpoint: t.Optional[str] = None,
  342. view_func: t.Optional[t.Callable] = None,
  343. provide_automatic_options: t.Optional[bool] = None,
  344. **options: t.Any,
  345. ) -> None:
  346. """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for
  347. the :func:`url_for` function is prefixed with the name of the blueprint.
  348. """
  349. if endpoint and "." in endpoint:
  350. raise ValueError("'endpoint' may not contain a dot '.' character.")
  351. if view_func and hasattr(view_func, "__name__") and "." in view_func.__name__:
  352. raise ValueError("'view_func' name may not contain a dot '.' character.")
  353. self.record(
  354. lambda s: s.add_url_rule(
  355. rule,
  356. endpoint,
  357. view_func,
  358. provide_automatic_options=provide_automatic_options,
  359. **options,
  360. )
  361. )
  362. def app_template_filter(
  363. self, name: t.Optional[str] = None
  364. ) -> t.Callable[[TemplateFilterCallable], TemplateFilterCallable]:
  365. """Register a custom template filter, available application wide. Like
  366. :meth:`Flask.template_filter` but for a blueprint.
  367. :param name: the optional name of the filter, otherwise the
  368. function name will be used.
  369. """
  370. def decorator(f: TemplateFilterCallable) -> TemplateFilterCallable:
  371. self.add_app_template_filter(f, name=name)
  372. return f
  373. return decorator
  374. def add_app_template_filter(
  375. self, f: TemplateFilterCallable, name: t.Optional[str] = None
  376. ) -> None:
  377. """Register a custom template filter, available application wide. Like
  378. :meth:`Flask.add_template_filter` but for a blueprint. Works exactly
  379. like the :meth:`app_template_filter` decorator.
  380. :param name: the optional name of the filter, otherwise the
  381. function name will be used.
  382. """
  383. def register_template(state: BlueprintSetupState) -> None:
  384. state.app.jinja_env.filters[name or f.__name__] = f
  385. self.record_once(register_template)
  386. def app_template_test(
  387. self, name: t.Optional[str] = None
  388. ) -> t.Callable[[TemplateTestCallable], TemplateTestCallable]:
  389. """Register a custom template test, available application wide. Like
  390. :meth:`Flask.template_test` but for a blueprint.
  391. .. versionadded:: 0.10
  392. :param name: the optional name of the test, otherwise the
  393. function name will be used.
  394. """
  395. def decorator(f: TemplateTestCallable) -> TemplateTestCallable:
  396. self.add_app_template_test(f, name=name)
  397. return f
  398. return decorator
  399. def add_app_template_test(
  400. self, f: TemplateTestCallable, name: t.Optional[str] = None
  401. ) -> None:
  402. """Register a custom template test, available application wide. Like
  403. :meth:`Flask.add_template_test` but for a blueprint. Works exactly
  404. like the :meth:`app_template_test` decorator.
  405. .. versionadded:: 0.10
  406. :param name: the optional name of the test, otherwise the
  407. function name will be used.
  408. """
  409. def register_template(state: BlueprintSetupState) -> None:
  410. state.app.jinja_env.tests[name or f.__name__] = f
  411. self.record_once(register_template)
  412. def app_template_global(
  413. self, name: t.Optional[str] = None
  414. ) -> t.Callable[[TemplateGlobalCallable], TemplateGlobalCallable]:
  415. """Register a custom template global, available application wide. Like
  416. :meth:`Flask.template_global` but for a blueprint.
  417. .. versionadded:: 0.10
  418. :param name: the optional name of the global, otherwise the
  419. function name will be used.
  420. """
  421. def decorator(f: TemplateGlobalCallable) -> TemplateGlobalCallable:
  422. self.add_app_template_global(f, name=name)
  423. return f
  424. return decorator
  425. def add_app_template_global(
  426. self, f: TemplateGlobalCallable, name: t.Optional[str] = None
  427. ) -> None:
  428. """Register a custom template global, available application wide. Like
  429. :meth:`Flask.add_template_global` but for a blueprint. Works exactly
  430. like the :meth:`app_template_global` decorator.
  431. .. versionadded:: 0.10
  432. :param name: the optional name of the global, otherwise the
  433. function name will be used.
  434. """
  435. def register_template(state: BlueprintSetupState) -> None:
  436. state.app.jinja_env.globals[name or f.__name__] = f
  437. self.record_once(register_template)
  438. def before_app_request(self, f: BeforeRequestCallable) -> BeforeRequestCallable:
  439. """Like :meth:`Flask.before_request`. Such a function is executed
  440. before each request, even if outside of a blueprint.
  441. """
  442. self.record_once(
  443. lambda s: s.app.before_request_funcs.setdefault(None, []).append(f)
  444. )
  445. return f
  446. def before_app_first_request(
  447. self, f: BeforeFirstRequestCallable
  448. ) -> BeforeFirstRequestCallable:
  449. """Like :meth:`Flask.before_first_request`. Such a function is
  450. executed before the first request to the application.
  451. """
  452. self.record_once(lambda s: s.app.before_first_request_funcs.append(f))
  453. return f
  454. def after_app_request(self, f: AfterRequestCallable) -> AfterRequestCallable:
  455. """Like :meth:`Flask.after_request` but for a blueprint. Such a function
  456. is executed after each request, even if outside of the blueprint.
  457. """
  458. self.record_once(
  459. lambda s: s.app.after_request_funcs.setdefault(None, []).append(f)
  460. )
  461. return f
  462. def teardown_app_request(self, f: TeardownCallable) -> TeardownCallable:
  463. """Like :meth:`Flask.teardown_request` but for a blueprint. Such a
  464. function is executed when tearing down each request, even if outside of
  465. the blueprint.
  466. """
  467. self.record_once(
  468. lambda s: s.app.teardown_request_funcs.setdefault(None, []).append(f)
  469. )
  470. return f
  471. def app_context_processor(
  472. self, f: TemplateContextProcessorCallable
  473. ) -> TemplateContextProcessorCallable:
  474. """Like :meth:`Flask.context_processor` but for a blueprint. Such a
  475. function is executed each request, even if outside of the blueprint.
  476. """
  477. self.record_once(
  478. lambda s: s.app.template_context_processors.setdefault(None, []).append(f)
  479. )
  480. return f
  481. def app_errorhandler(self, code: t.Union[t.Type[Exception], int]) -> t.Callable:
  482. """Like :meth:`Flask.errorhandler` but for a blueprint. This
  483. handler is used for all requests, even if outside of the blueprint.
  484. """
  485. def decorator(
  486. f: "ErrorHandlerCallable[Exception]",
  487. ) -> "ErrorHandlerCallable[Exception]":
  488. self.record_once(lambda s: s.app.errorhandler(code)(f))
  489. return f
  490. return decorator
  491. def app_url_value_preprocessor(
  492. self, f: URLValuePreprocessorCallable
  493. ) -> URLValuePreprocessorCallable:
  494. """Same as :meth:`url_value_preprocessor` but application wide."""
  495. self.record_once(
  496. lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)
  497. )
  498. return f
  499. def app_url_defaults(self, f: URLDefaultCallable) -> URLDefaultCallable:
  500. """Same as :meth:`url_defaults` but application wide."""
  501. self.record_once(
  502. lambda s: s.app.url_default_functions.setdefault(None, []).append(f)
  503. )
  504. return f