You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

604 lines
23KB

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