1
0

blueprints.py 21 KB

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