app.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964
  1. from __future__ import annotations
  2. import logging
  3. import os
  4. import sys
  5. import typing as t
  6. from datetime import timedelta
  7. from itertools import chain
  8. from werkzeug.exceptions import Aborter
  9. from werkzeug.exceptions import BadRequest
  10. from werkzeug.exceptions import BadRequestKeyError
  11. from werkzeug.routing import BuildError
  12. from werkzeug.routing import Map
  13. from werkzeug.routing import Rule
  14. from werkzeug.sansio.response import Response
  15. from werkzeug.utils import cached_property
  16. from werkzeug.utils import redirect as _wz_redirect
  17. from .. import typing as ft
  18. from ..config import Config
  19. from ..config import ConfigAttribute
  20. from ..ctx import _AppCtxGlobals
  21. from ..helpers import _split_blueprint_path
  22. from ..helpers import get_debug_flag
  23. from ..json.provider import DefaultJSONProvider
  24. from ..json.provider import JSONProvider
  25. from ..logging import create_logger
  26. from ..templating import DispatchingJinjaLoader
  27. from ..templating import Environment
  28. from .scaffold import _endpoint_from_view_func
  29. from .scaffold import find_package
  30. from .scaffold import Scaffold
  31. from .scaffold import setupmethod
  32. if t.TYPE_CHECKING: # pragma: no cover
  33. from werkzeug.wrappers import Response as BaseResponse
  34. from ..testing import FlaskClient
  35. from ..testing import FlaskCliRunner
  36. from .blueprints import Blueprint
  37. T_shell_context_processor = t.TypeVar(
  38. "T_shell_context_processor", bound=ft.ShellContextProcessorCallable
  39. )
  40. T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
  41. T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
  42. T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
  43. T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)
  44. def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
  45. if value is None or isinstance(value, timedelta):
  46. return value
  47. return timedelta(seconds=value)
  48. class App(Scaffold):
  49. """The flask object implements a WSGI application and acts as the central
  50. object. It is passed the name of the module or package of the
  51. application. Once it is created it will act as a central registry for
  52. the view functions, the URL rules, template configuration and much more.
  53. The name of the package is used to resolve resources from inside the
  54. package or the folder the module is contained in depending on if the
  55. package parameter resolves to an actual python package (a folder with
  56. an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
  57. For more information about resource loading, see :func:`open_resource`.
  58. Usually you create a :class:`Flask` instance in your main module or
  59. in the :file:`__init__.py` file of your package like this::
  60. from flask import Flask
  61. app = Flask(__name__)
  62. .. admonition:: About the First Parameter
  63. The idea of the first parameter is to give Flask an idea of what
  64. belongs to your application. This name is used to find resources
  65. on the filesystem, can be used by extensions to improve debugging
  66. information and a lot more.
  67. So it's important what you provide there. If you are using a single
  68. module, `__name__` is always the correct value. If you however are
  69. using a package, it's usually recommended to hardcode the name of
  70. your package there.
  71. For example if your application is defined in :file:`yourapplication/app.py`
  72. you should create it with one of the two versions below::
  73. app = Flask('yourapplication')
  74. app = Flask(__name__.split('.')[0])
  75. Why is that? The application will work even with `__name__`, thanks
  76. to how resources are looked up. However it will make debugging more
  77. painful. Certain extensions can make assumptions based on the
  78. import name of your application. For example the Flask-SQLAlchemy
  79. extension will look for the code in your application that triggered
  80. an SQL query in debug mode. If the import name is not properly set
  81. up, that debugging information is lost. (For example it would only
  82. pick up SQL queries in `yourapplication.app` and not
  83. `yourapplication.views.frontend`)
  84. .. versionadded:: 0.7
  85. The `static_url_path`, `static_folder`, and `template_folder`
  86. parameters were added.
  87. .. versionadded:: 0.8
  88. The `instance_path` and `instance_relative_config` parameters were
  89. added.
  90. .. versionadded:: 0.11
  91. The `root_path` parameter was added.
  92. .. versionadded:: 1.0
  93. The ``host_matching`` and ``static_host`` parameters were added.
  94. .. versionadded:: 1.0
  95. The ``subdomain_matching`` parameter was added. Subdomain
  96. matching needs to be enabled manually now. Setting
  97. :data:`SERVER_NAME` does not implicitly enable it.
  98. :param import_name: the name of the application package
  99. :param static_url_path: can be used to specify a different path for the
  100. static files on the web. Defaults to the name
  101. of the `static_folder` folder.
  102. :param static_folder: The folder with static files that is served at
  103. ``static_url_path``. Relative to the application ``root_path``
  104. or an absolute path. Defaults to ``'static'``.
  105. :param static_host: the host to use when adding the static route.
  106. Defaults to None. Required when using ``host_matching=True``
  107. with a ``static_folder`` configured.
  108. :param host_matching: set ``url_map.host_matching`` attribute.
  109. Defaults to False.
  110. :param subdomain_matching: consider the subdomain relative to
  111. :data:`SERVER_NAME` when matching routes. Defaults to False.
  112. :param template_folder: the folder that contains the templates that should
  113. be used by the application. Defaults to
  114. ``'templates'`` folder in the root path of the
  115. application.
  116. :param instance_path: An alternative instance path for the application.
  117. By default the folder ``'instance'`` next to the
  118. package or module is assumed to be the instance
  119. path.
  120. :param instance_relative_config: if set to ``True`` relative filenames
  121. for loading the config are assumed to
  122. be relative to the instance path instead
  123. of the application root.
  124. :param root_path: The path to the root of the application files.
  125. This should only be set manually when it can't be detected
  126. automatically, such as for namespace packages.
  127. """
  128. #: The class of the object assigned to :attr:`aborter`, created by
  129. #: :meth:`create_aborter`. That object is called by
  130. #: :func:`flask.abort` to raise HTTP errors, and can be
  131. #: called directly as well.
  132. #:
  133. #: Defaults to :class:`werkzeug.exceptions.Aborter`.
  134. #:
  135. #: .. versionadded:: 2.2
  136. aborter_class = Aborter
  137. #: The class that is used for the Jinja environment.
  138. #:
  139. #: .. versionadded:: 0.11
  140. jinja_environment = Environment
  141. #: The class that is used for the :data:`~flask.g` instance.
  142. #:
  143. #: Example use cases for a custom class:
  144. #:
  145. #: 1. Store arbitrary attributes on flask.g.
  146. #: 2. Add a property for lazy per-request database connectors.
  147. #: 3. Return None instead of AttributeError on unexpected attributes.
  148. #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.
  149. #:
  150. #: In Flask 0.9 this property was called `request_globals_class` but it
  151. #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the
  152. #: flask.g object is now application context scoped.
  153. #:
  154. #: .. versionadded:: 0.10
  155. app_ctx_globals_class = _AppCtxGlobals
  156. #: The class that is used for the ``config`` attribute of this app.
  157. #: Defaults to :class:`~flask.Config`.
  158. #:
  159. #: Example use cases for a custom class:
  160. #:
  161. #: 1. Default values for certain config options.
  162. #: 2. Access to config values through attributes in addition to keys.
  163. #:
  164. #: .. versionadded:: 0.11
  165. config_class = Config
  166. #: The testing flag. Set this to ``True`` to enable the test mode of
  167. #: Flask extensions (and in the future probably also Flask itself).
  168. #: For example this might activate test helpers that have an
  169. #: additional runtime cost which should not be enabled by default.
  170. #:
  171. #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
  172. #: default it's implicitly enabled.
  173. #:
  174. #: This attribute can also be configured from the config with the
  175. #: ``TESTING`` configuration key. Defaults to ``False``.
  176. testing = ConfigAttribute[bool]("TESTING")
  177. #: If a secret key is set, cryptographic components can use this to
  178. #: sign cookies and other things. Set this to a complex random value
  179. #: when you want to use the secure cookie for instance.
  180. #:
  181. #: This attribute can also be configured from the config with the
  182. #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.
  183. secret_key = ConfigAttribute[t.Union[str, bytes, None]]("SECRET_KEY")
  184. #: A :class:`~datetime.timedelta` which is used to set the expiration
  185. #: date of a permanent session. The default is 31 days which makes a
  186. #: permanent session survive for roughly one month.
  187. #:
  188. #: This attribute can also be configured from the config with the
  189. #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to
  190. #: ``timedelta(days=31)``
  191. permanent_session_lifetime = ConfigAttribute[timedelta](
  192. "PERMANENT_SESSION_LIFETIME",
  193. get_converter=_make_timedelta, # type: ignore[arg-type]
  194. )
  195. json_provider_class: type[JSONProvider] = DefaultJSONProvider
  196. """A subclass of :class:`~flask.json.provider.JSONProvider`. An
  197. instance is created and assigned to :attr:`app.json` when creating
  198. the app.
  199. The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses
  200. Python's built-in :mod:`json` library. A different provider can use
  201. a different JSON library.
  202. .. versionadded:: 2.2
  203. """
  204. #: Options that are passed to the Jinja environment in
  205. #: :meth:`create_jinja_environment`. Changing these options after
  206. #: the environment is created (accessing :attr:`jinja_env`) will
  207. #: have no effect.
  208. #:
  209. #: .. versionchanged:: 1.1.0
  210. #: This is a ``dict`` instead of an ``ImmutableDict`` to allow
  211. #: easier configuration.
  212. #:
  213. jinja_options: dict[str, t.Any] = {}
  214. #: The rule object to use for URL rules created. This is used by
  215. #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.
  216. #:
  217. #: .. versionadded:: 0.7
  218. url_rule_class = Rule
  219. #: The map object to use for storing the URL rules and routing
  220. #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.
  221. #:
  222. #: .. versionadded:: 1.1.0
  223. url_map_class = Map
  224. #: The :meth:`test_client` method creates an instance of this test
  225. #: client class. Defaults to :class:`~flask.testing.FlaskClient`.
  226. #:
  227. #: .. versionadded:: 0.7
  228. test_client_class: type[FlaskClient] | None = None
  229. #: The :class:`~click.testing.CliRunner` subclass, by default
  230. #: :class:`~flask.testing.FlaskCliRunner` that is used by
  231. #: :meth:`test_cli_runner`. Its ``__init__`` method should take a
  232. #: Flask app object as the first argument.
  233. #:
  234. #: .. versionadded:: 1.0
  235. test_cli_runner_class: type[FlaskCliRunner] | None = None
  236. default_config: dict[str, t.Any]
  237. response_class: type[Response]
  238. def __init__(
  239. self,
  240. import_name: str,
  241. static_url_path: str | None = None,
  242. static_folder: str | os.PathLike[str] | None = "static",
  243. static_host: str | None = None,
  244. host_matching: bool = False,
  245. subdomain_matching: bool = False,
  246. template_folder: str | os.PathLike[str] | None = "templates",
  247. instance_path: str | None = None,
  248. instance_relative_config: bool = False,
  249. root_path: str | None = None,
  250. ) -> None:
  251. super().__init__(
  252. import_name=import_name,
  253. static_folder=static_folder,
  254. static_url_path=static_url_path,
  255. template_folder=template_folder,
  256. root_path=root_path,
  257. )
  258. if instance_path is None:
  259. instance_path = self.auto_find_instance_path()
  260. elif not os.path.isabs(instance_path):
  261. raise ValueError(
  262. "If an instance path is provided it must be absolute."
  263. " A relative path was given instead."
  264. )
  265. #: Holds the path to the instance folder.
  266. #:
  267. #: .. versionadded:: 0.8
  268. self.instance_path = instance_path
  269. #: The configuration dictionary as :class:`Config`. This behaves
  270. #: exactly like a regular dictionary but supports additional methods
  271. #: to load a config from files.
  272. self.config = self.make_config(instance_relative_config)
  273. #: An instance of :attr:`aborter_class` created by
  274. #: :meth:`make_aborter`. This is called by :func:`flask.abort`
  275. #: to raise HTTP errors, and can be called directly as well.
  276. #:
  277. #: .. versionadded:: 2.2
  278. #: Moved from ``flask.abort``, which calls this object.
  279. self.aborter = self.make_aborter()
  280. self.json: JSONProvider = self.json_provider_class(self)
  281. """Provides access to JSON methods. Functions in ``flask.json``
  282. will call methods on this provider when the application context
  283. is active. Used for handling JSON requests and responses.
  284. An instance of :attr:`json_provider_class`. Can be customized by
  285. changing that attribute on a subclass, or by assigning to this
  286. attribute afterwards.
  287. The default, :class:`~flask.json.provider.DefaultJSONProvider`,
  288. uses Python's built-in :mod:`json` library. A different provider
  289. can use a different JSON library.
  290. .. versionadded:: 2.2
  291. """
  292. #: A list of functions that are called by
  293. #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a
  294. #: :exc:`~werkzeug.routing.BuildError`. Each function is called
  295. #: with ``error``, ``endpoint`` and ``values``. If a function
  296. #: returns ``None`` or raises a ``BuildError``, it is skipped.
  297. #: Otherwise, its return value is returned by ``url_for``.
  298. #:
  299. #: .. versionadded:: 0.9
  300. self.url_build_error_handlers: list[
  301. t.Callable[[Exception, str, dict[str, t.Any]], str]
  302. ] = []
  303. #: A list of functions that are called when the application context
  304. #: is destroyed. Since the application context is also torn down
  305. #: if the request ends this is the place to store code that disconnects
  306. #: from databases.
  307. #:
  308. #: .. versionadded:: 0.9
  309. self.teardown_appcontext_funcs: list[ft.TeardownCallable] = []
  310. #: A list of shell context processor functions that should be run
  311. #: when a shell context is created.
  312. #:
  313. #: .. versionadded:: 0.11
  314. self.shell_context_processors: list[ft.ShellContextProcessorCallable] = []
  315. #: Maps registered blueprint names to blueprint objects. The
  316. #: dict retains the order the blueprints were registered in.
  317. #: Blueprints can be registered multiple times, this dict does
  318. #: not track how often they were attached.
  319. #:
  320. #: .. versionadded:: 0.7
  321. self.blueprints: dict[str, Blueprint] = {}
  322. #: a place where extensions can store application specific state. For
  323. #: example this is where an extension could store database engines and
  324. #: similar things.
  325. #:
  326. #: The key must match the name of the extension module. For example in
  327. #: case of a "Flask-Foo" extension in `flask_foo`, the key would be
  328. #: ``'foo'``.
  329. #:
  330. #: .. versionadded:: 0.7
  331. self.extensions: dict[str, t.Any] = {}
  332. #: The :class:`~werkzeug.routing.Map` for this instance. You can use
  333. #: this to change the routing converters after the class was created
  334. #: but before any routes are connected. Example::
  335. #:
  336. #: from werkzeug.routing import BaseConverter
  337. #:
  338. #: class ListConverter(BaseConverter):
  339. #: def to_python(self, value):
  340. #: return value.split(',')
  341. #: def to_url(self, values):
  342. #: return ','.join(super(ListConverter, self).to_url(value)
  343. #: for value in values)
  344. #:
  345. #: app = Flask(__name__)
  346. #: app.url_map.converters['list'] = ListConverter
  347. self.url_map = self.url_map_class(host_matching=host_matching)
  348. self.subdomain_matching = subdomain_matching
  349. # tracks internally if the application already handled at least one
  350. # request.
  351. self._got_first_request = False
  352. def _check_setup_finished(self, f_name: str) -> None:
  353. if self._got_first_request:
  354. raise AssertionError(
  355. f"The setup method '{f_name}' can no longer be called"
  356. " on the application. It has already handled its first"
  357. " request, any changes will not be applied"
  358. " consistently.\n"
  359. "Make sure all imports, decorators, functions, etc."
  360. " needed to set up the application are done before"
  361. " running it."
  362. )
  363. @cached_property
  364. def name(self) -> str: # type: ignore
  365. """The name of the application. This is usually the import name
  366. with the difference that it's guessed from the run file if the
  367. import name is main. This name is used as a display name when
  368. Flask needs the name of the application. It can be set and overridden
  369. to change the value.
  370. .. versionadded:: 0.8
  371. """
  372. if self.import_name == "__main__":
  373. fn: str | None = getattr(sys.modules["__main__"], "__file__", None)
  374. if fn is None:
  375. return "__main__"
  376. return os.path.splitext(os.path.basename(fn))[0]
  377. return self.import_name
  378. @cached_property
  379. def logger(self) -> logging.Logger:
  380. """A standard Python :class:`~logging.Logger` for the app, with
  381. the same name as :attr:`name`.
  382. In debug mode, the logger's :attr:`~logging.Logger.level` will
  383. be set to :data:`~logging.DEBUG`.
  384. If there are no handlers configured, a default handler will be
  385. added. See :doc:`/logging` for more information.
  386. .. versionchanged:: 1.1.0
  387. The logger takes the same name as :attr:`name` rather than
  388. hard-coding ``"flask.app"``.
  389. .. versionchanged:: 1.0.0
  390. Behavior was simplified. The logger is always named
  391. ``"flask.app"``. The level is only set during configuration,
  392. it doesn't check ``app.debug`` each time. Only one format is
  393. used, not different ones depending on ``app.debug``. No
  394. handlers are removed, and a handler is only added if no
  395. handlers are already configured.
  396. .. versionadded:: 0.3
  397. """
  398. return create_logger(self)
  399. @cached_property
  400. def jinja_env(self) -> Environment:
  401. """The Jinja environment used to load templates.
  402. The environment is created the first time this property is
  403. accessed. Changing :attr:`jinja_options` after that will have no
  404. effect.
  405. """
  406. return self.create_jinja_environment()
  407. def create_jinja_environment(self) -> Environment:
  408. raise NotImplementedError()
  409. def make_config(self, instance_relative: bool = False) -> Config:
  410. """Used to create the config attribute by the Flask constructor.
  411. The `instance_relative` parameter is passed in from the constructor
  412. of Flask (there named `instance_relative_config`) and indicates if
  413. the config should be relative to the instance path or the root path
  414. of the application.
  415. .. versionadded:: 0.8
  416. """
  417. root_path = self.root_path
  418. if instance_relative:
  419. root_path = self.instance_path
  420. defaults = dict(self.default_config)
  421. defaults["DEBUG"] = get_debug_flag()
  422. return self.config_class(root_path, defaults)
  423. def make_aborter(self) -> Aborter:
  424. """Create the object to assign to :attr:`aborter`. That object
  425. is called by :func:`flask.abort` to raise HTTP errors, and can
  426. be called directly as well.
  427. By default, this creates an instance of :attr:`aborter_class`,
  428. which defaults to :class:`werkzeug.exceptions.Aborter`.
  429. .. versionadded:: 2.2
  430. """
  431. return self.aborter_class()
  432. def auto_find_instance_path(self) -> str:
  433. """Tries to locate the instance path if it was not provided to the
  434. constructor of the application class. It will basically calculate
  435. the path to a folder named ``instance`` next to your main file or
  436. the package.
  437. .. versionadded:: 0.8
  438. """
  439. prefix, package_path = find_package(self.import_name)
  440. if prefix is None:
  441. return os.path.join(package_path, "instance")
  442. return os.path.join(prefix, "var", f"{self.name}-instance")
  443. def create_global_jinja_loader(self) -> DispatchingJinjaLoader:
  444. """Creates the loader for the Jinja2 environment. Can be used to
  445. override just the loader and keeping the rest unchanged. It's
  446. discouraged to override this function. Instead one should override
  447. the :meth:`jinja_loader` function instead.
  448. The global loader dispatches between the loaders of the application
  449. and the individual blueprints.
  450. .. versionadded:: 0.7
  451. """
  452. return DispatchingJinjaLoader(self)
  453. def select_jinja_autoescape(self, filename: str) -> bool:
  454. """Returns ``True`` if autoescaping should be active for the given
  455. template name. If no template name is given, returns `True`.
  456. .. versionchanged:: 2.2
  457. Autoescaping is now enabled by default for ``.svg`` files.
  458. .. versionadded:: 0.5
  459. """
  460. if filename is None:
  461. return True
  462. return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))
  463. @property
  464. def debug(self) -> bool:
  465. """Whether debug mode is enabled. When using ``flask run`` to start the
  466. development server, an interactive debugger will be shown for unhandled
  467. exceptions, and the server will be reloaded when code changes. This maps to the
  468. :data:`DEBUG` config key. It may not behave as expected if set late.
  469. **Do not enable debug mode when deploying in production.**
  470. Default: ``False``
  471. """
  472. return self.config["DEBUG"] # type: ignore[no-any-return]
  473. @debug.setter
  474. def debug(self, value: bool) -> None:
  475. self.config["DEBUG"] = value
  476. if self.config["TEMPLATES_AUTO_RELOAD"] is None:
  477. self.jinja_env.auto_reload = value
  478. @setupmethod
  479. def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:
  480. """Register a :class:`~flask.Blueprint` on the application. Keyword
  481. arguments passed to this method will override the defaults set on the
  482. blueprint.
  483. Calls the blueprint's :meth:`~flask.Blueprint.register` method after
  484. recording the blueprint in the application's :attr:`blueprints`.
  485. :param blueprint: The blueprint to register.
  486. :param url_prefix: Blueprint routes will be prefixed with this.
  487. :param subdomain: Blueprint routes will match on this subdomain.
  488. :param url_defaults: Blueprint routes will use these default values for
  489. view arguments.
  490. :param options: Additional keyword arguments are passed to
  491. :class:`~flask.blueprints.BlueprintSetupState`. They can be
  492. accessed in :meth:`~flask.Blueprint.record` callbacks.
  493. .. versionchanged:: 2.0.1
  494. The ``name`` option can be used to change the (pre-dotted)
  495. name the blueprint is registered with. This allows the same
  496. blueprint to be registered multiple times with unique names
  497. for ``url_for``.
  498. .. versionadded:: 0.7
  499. """
  500. blueprint.register(self, options)
  501. def iter_blueprints(self) -> t.ValuesView[Blueprint]:
  502. """Iterates over all blueprints by the order they were registered.
  503. .. versionadded:: 0.11
  504. """
  505. return self.blueprints.values()
  506. @setupmethod
  507. def add_url_rule(
  508. self,
  509. rule: str,
  510. endpoint: str | None = None,
  511. view_func: ft.RouteCallable | None = None,
  512. provide_automatic_options: bool | None = None,
  513. **options: t.Any,
  514. ) -> None:
  515. if endpoint is None:
  516. endpoint = _endpoint_from_view_func(view_func) # type: ignore
  517. options["endpoint"] = endpoint
  518. methods = options.pop("methods", None)
  519. # if the methods are not given and the view_func object knows its
  520. # methods we can use that instead. If neither exists, we go with
  521. # a tuple of only ``GET`` as default.
  522. if methods is None:
  523. methods = getattr(view_func, "methods", None) or ("GET",)
  524. if isinstance(methods, str):
  525. raise TypeError(
  526. "Allowed methods must be a list of strings, for"
  527. ' example: @app.route(..., methods=["POST"])'
  528. )
  529. methods = {item.upper() for item in methods}
  530. # Methods that should always be added
  531. required_methods: set[str] = set(getattr(view_func, "required_methods", ()))
  532. # starting with Flask 0.8 the view_func object can disable and
  533. # force-enable the automatic options handling.
  534. if provide_automatic_options is None:
  535. provide_automatic_options = getattr(
  536. view_func, "provide_automatic_options", None
  537. )
  538. if provide_automatic_options is None:
  539. if "OPTIONS" not in methods and self.config["PROVIDE_AUTOMATIC_OPTIONS"]:
  540. provide_automatic_options = True
  541. required_methods.add("OPTIONS")
  542. else:
  543. provide_automatic_options = False
  544. # Add the required methods now.
  545. methods |= required_methods
  546. rule_obj = self.url_rule_class(rule, methods=methods, **options)
  547. rule_obj.provide_automatic_options = provide_automatic_options # type: ignore[attr-defined]
  548. self.url_map.add(rule_obj)
  549. if view_func is not None:
  550. old_func = self.view_functions.get(endpoint)
  551. if old_func is not None and old_func != view_func:
  552. raise AssertionError(
  553. "View function mapping is overwriting an existing"
  554. f" endpoint function: {endpoint}"
  555. )
  556. self.view_functions[endpoint] = view_func
  557. @setupmethod
  558. def template_filter(
  559. self, name: str | None = None
  560. ) -> t.Callable[[T_template_filter], T_template_filter]:
  561. """A decorator that is used to register custom template filter.
  562. You can specify a name for the filter, otherwise the function
  563. name will be used. Example::
  564. @app.template_filter()
  565. def reverse(s):
  566. return s[::-1]
  567. :param name: the optional name of the filter, otherwise the
  568. function name will be used.
  569. """
  570. def decorator(f: T_template_filter) -> T_template_filter:
  571. self.add_template_filter(f, name=name)
  572. return f
  573. return decorator
  574. @setupmethod
  575. def add_template_filter(
  576. self, f: ft.TemplateFilterCallable, name: str | None = None
  577. ) -> None:
  578. """Register a custom template filter. Works exactly like the
  579. :meth:`template_filter` decorator.
  580. :param name: the optional name of the filter, otherwise the
  581. function name will be used.
  582. """
  583. self.jinja_env.filters[name or f.__name__] = f
  584. @setupmethod
  585. def template_test(
  586. self, name: str | None = None
  587. ) -> t.Callable[[T_template_test], T_template_test]:
  588. """A decorator that is used to register custom template test.
  589. You can specify a name for the test, otherwise the function
  590. name will be used. Example::
  591. @app.template_test()
  592. def is_prime(n):
  593. if n == 2:
  594. return True
  595. for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
  596. if n % i == 0:
  597. return False
  598. return True
  599. .. versionadded:: 0.10
  600. :param name: the optional name of the test, otherwise the
  601. function name will be used.
  602. """
  603. def decorator(f: T_template_test) -> T_template_test:
  604. self.add_template_test(f, name=name)
  605. return f
  606. return decorator
  607. @setupmethod
  608. def add_template_test(
  609. self, f: ft.TemplateTestCallable, name: str | None = None
  610. ) -> None:
  611. """Register a custom template test. Works exactly like the
  612. :meth:`template_test` decorator.
  613. .. versionadded:: 0.10
  614. :param name: the optional name of the test, otherwise the
  615. function name will be used.
  616. """
  617. self.jinja_env.tests[name or f.__name__] = f
  618. @setupmethod
  619. def template_global(
  620. self, name: str | None = None
  621. ) -> t.Callable[[T_template_global], T_template_global]:
  622. """A decorator that is used to register a custom template global function.
  623. You can specify a name for the global function, otherwise the function
  624. name will be used. Example::
  625. @app.template_global()
  626. def double(n):
  627. return 2 * n
  628. .. versionadded:: 0.10
  629. :param name: the optional name of the global function, otherwise the
  630. function name will be used.
  631. """
  632. def decorator(f: T_template_global) -> T_template_global:
  633. self.add_template_global(f, name=name)
  634. return f
  635. return decorator
  636. @setupmethod
  637. def add_template_global(
  638. self, f: ft.TemplateGlobalCallable, name: str | None = None
  639. ) -> None:
  640. """Register a custom template global function. Works exactly like the
  641. :meth:`template_global` decorator.
  642. .. versionadded:: 0.10
  643. :param name: the optional name of the global function, otherwise the
  644. function name will be used.
  645. """
  646. self.jinja_env.globals[name or f.__name__] = f
  647. @setupmethod
  648. def teardown_appcontext(self, f: T_teardown) -> T_teardown:
  649. """Registers a function to be called when the application
  650. context is popped. The application context is typically popped
  651. after the request context for each request, at the end of CLI
  652. commands, or after a manually pushed context ends.
  653. .. code-block:: python
  654. with app.app_context():
  655. ...
  656. When the ``with`` block exits (or ``ctx.pop()`` is called), the
  657. teardown functions are called just before the app context is
  658. made inactive. Since a request context typically also manages an
  659. application context it would also be called when you pop a
  660. request context.
  661. When a teardown function was called because of an unhandled
  662. exception it will be passed an error object. If an
  663. :meth:`errorhandler` is registered, it will handle the exception
  664. and the teardown will not receive it.
  665. Teardown functions must avoid raising exceptions. If they
  666. execute code that might fail they must surround that code with a
  667. ``try``/``except`` block and log any errors.
  668. The return values of teardown functions are ignored.
  669. .. versionadded:: 0.9
  670. """
  671. self.teardown_appcontext_funcs.append(f)
  672. return f
  673. @setupmethod
  674. def shell_context_processor(
  675. self, f: T_shell_context_processor
  676. ) -> T_shell_context_processor:
  677. """Registers a shell context processor function.
  678. .. versionadded:: 0.11
  679. """
  680. self.shell_context_processors.append(f)
  681. return f
  682. def _find_error_handler(
  683. self, e: Exception, blueprints: list[str]
  684. ) -> ft.ErrorHandlerCallable | None:
  685. """Return a registered error handler for an exception in this order:
  686. blueprint handler for a specific code, app handler for a specific code,
  687. blueprint handler for an exception class, app handler for an exception
  688. class, or ``None`` if a suitable handler is not found.
  689. """
  690. exc_class, code = self._get_exc_class_and_code(type(e))
  691. names = (*blueprints, None)
  692. for c in (code, None) if code is not None else (None,):
  693. for name in names:
  694. handler_map = self.error_handler_spec[name][c]
  695. if not handler_map:
  696. continue
  697. for cls in exc_class.__mro__:
  698. handler = handler_map.get(cls)
  699. if handler is not None:
  700. return handler
  701. return None
  702. def trap_http_exception(self, e: Exception) -> bool:
  703. """Checks if an HTTP exception should be trapped or not. By default
  704. this will return ``False`` for all exceptions except for a bad request
  705. key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
  706. also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
  707. This is called for all HTTP exceptions raised by a view function.
  708. If it returns ``True`` for any exception the error handler for this
  709. exception is not called and it shows up as regular exception in the
  710. traceback. This is helpful for debugging implicitly raised HTTP
  711. exceptions.
  712. .. versionchanged:: 1.0
  713. Bad request errors are not trapped by default in debug mode.
  714. .. versionadded:: 0.8
  715. """
  716. if self.config["TRAP_HTTP_EXCEPTIONS"]:
  717. return True
  718. trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]
  719. # if unset, trap key errors in debug mode
  720. if (
  721. trap_bad_request is None
  722. and self.debug
  723. and isinstance(e, BadRequestKeyError)
  724. ):
  725. return True
  726. if trap_bad_request:
  727. return isinstance(e, BadRequest)
  728. return False
  729. def should_ignore_error(self, error: BaseException | None) -> bool:
  730. """This is called to figure out if an error should be ignored
  731. or not as far as the teardown system is concerned. If this
  732. function returns ``True`` then the teardown handlers will not be
  733. passed the error.
  734. .. versionadded:: 0.10
  735. """
  736. return False
  737. def redirect(self, location: str, code: int = 302) -> BaseResponse:
  738. """Create a redirect response object.
  739. This is called by :func:`flask.redirect`, and can be called
  740. directly as well.
  741. :param location: The URL to redirect to.
  742. :param code: The status code for the redirect.
  743. .. versionadded:: 2.2
  744. Moved from ``flask.redirect``, which calls this method.
  745. """
  746. return _wz_redirect(
  747. location,
  748. code=code,
  749. Response=self.response_class, # type: ignore[arg-type]
  750. )
  751. def inject_url_defaults(self, endpoint: str, values: dict[str, t.Any]) -> None:
  752. """Injects the URL defaults for the given endpoint directly into
  753. the values dictionary passed. This is used internally and
  754. automatically called on URL building.
  755. .. versionadded:: 0.7
  756. """
  757. names: t.Iterable[str | None] = (None,)
  758. # url_for may be called outside a request context, parse the
  759. # passed endpoint instead of using request.blueprints.
  760. if "." in endpoint:
  761. names = chain(
  762. names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))
  763. )
  764. for name in names:
  765. if name in self.url_default_functions:
  766. for func in self.url_default_functions[name]:
  767. func(endpoint, values)
  768. def handle_url_build_error(
  769. self, error: BuildError, endpoint: str, values: dict[str, t.Any]
  770. ) -> str:
  771. """Called by :meth:`.url_for` if a
  772. :exc:`~werkzeug.routing.BuildError` was raised. If this returns
  773. a value, it will be returned by ``url_for``, otherwise the error
  774. will be re-raised.
  775. Each function in :attr:`url_build_error_handlers` is called with
  776. ``error``, ``endpoint`` and ``values``. If a function returns
  777. ``None`` or raises a ``BuildError``, it is skipped. Otherwise,
  778. its return value is returned by ``url_for``.
  779. :param error: The active ``BuildError`` being handled.
  780. :param endpoint: The endpoint being built.
  781. :param values: The keyword arguments passed to ``url_for``.
  782. """
  783. for handler in self.url_build_error_handlers:
  784. try:
  785. rv = handler(error, endpoint, values)
  786. except BuildError as e:
  787. # make error available outside except block
  788. error = e
  789. else:
  790. if rv is not None:
  791. return rv
  792. # Re-raise if called with an active exception, otherwise raise
  793. # the passed in exception.
  794. if error is sys.exc_info()[1]:
  795. raise
  796. raise error