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 .blueprints import Blueprint
  35. from ..testing import FlaskClient
  36. from ..testing import FlaskCliRunner
  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("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("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(
  192. "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta
  193. )
  194. json_provider_class: type[JSONProvider] = DefaultJSONProvider
  195. """A subclass of :class:`~flask.json.provider.JSONProvider`. An
  196. instance is created and assigned to :attr:`app.json` when creating
  197. the app.
  198. The default, :class:`~flask.json.provider.DefaultJSONProvider`, uses
  199. Python's built-in :mod:`json` library. A different provider can use
  200. a different JSON library.
  201. .. versionadded:: 2.2
  202. """
  203. #: Options that are passed to the Jinja environment in
  204. #: :meth:`create_jinja_environment`. Changing these options after
  205. #: the environment is created (accessing :attr:`jinja_env`) will
  206. #: have no effect.
  207. #:
  208. #: .. versionchanged:: 1.1.0
  209. #: This is a ``dict`` instead of an ``ImmutableDict`` to allow
  210. #: easier configuration.
  211. #:
  212. jinja_options: dict = {}
  213. #: The rule object to use for URL rules created. This is used by
  214. #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.
  215. #:
  216. #: .. versionadded:: 0.7
  217. url_rule_class = Rule
  218. #: The map object to use for storing the URL rules and routing
  219. #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.
  220. #:
  221. #: .. versionadded:: 1.1.0
  222. url_map_class = Map
  223. #: The :meth:`test_client` method creates an instance of this test
  224. #: client class. Defaults to :class:`~flask.testing.FlaskClient`.
  225. #:
  226. #: .. versionadded:: 0.7
  227. test_client_class: type[FlaskClient] | None = None
  228. #: The :class:`~click.testing.CliRunner` subclass, by default
  229. #: :class:`~flask.testing.FlaskCliRunner` that is used by
  230. #: :meth:`test_cli_runner`. Its ``__init__`` method should take a
  231. #: Flask app object as the first argument.
  232. #:
  233. #: .. versionadded:: 1.0
  234. test_cli_runner_class: type[FlaskCliRunner] | None = None
  235. default_config: dict
  236. response_class: type[Response]
  237. def __init__(
  238. self,
  239. import_name: str,
  240. static_url_path: str | None = None,
  241. static_folder: str | os.PathLike | None = "static",
  242. static_host: str | None = None,
  243. host_matching: bool = False,
  244. subdomain_matching: bool = False,
  245. template_folder: str | os.PathLike | None = "templates",
  246. instance_path: str | None = None,
  247. instance_relative_config: bool = False,
  248. root_path: str | None = None,
  249. ):
  250. super().__init__(
  251. import_name=import_name,
  252. static_folder=static_folder,
  253. static_url_path=static_url_path,
  254. template_folder=template_folder,
  255. root_path=root_path,
  256. )
  257. if instance_path is None:
  258. instance_path = self.auto_find_instance_path()
  259. elif not os.path.isabs(instance_path):
  260. raise ValueError(
  261. "If an instance path is provided it must be absolute."
  262. " A relative path was given instead."
  263. )
  264. #: Holds the path to the instance folder.
  265. #:
  266. #: .. versionadded:: 0.8
  267. self.instance_path = instance_path
  268. #: The configuration dictionary as :class:`Config`. This behaves
  269. #: exactly like a regular dictionary but supports additional methods
  270. #: to load a config from files.
  271. self.config = self.make_config(instance_relative_config)
  272. #: An instance of :attr:`aborter_class` created by
  273. #: :meth:`make_aborter`. This is called by :func:`flask.abort`
  274. #: to raise HTTP errors, and can be called directly as well.
  275. #:
  276. #: .. versionadded:: 2.2
  277. #: Moved from ``flask.abort``, which calls this object.
  278. self.aborter = self.make_aborter()
  279. self.json: JSONProvider = self.json_provider_class(self)
  280. """Provides access to JSON methods. Functions in ``flask.json``
  281. will call methods on this provider when the application context
  282. is active. Used for handling JSON requests and responses.
  283. An instance of :attr:`json_provider_class`. Can be customized by
  284. changing that attribute on a subclass, or by assigning to this
  285. attribute afterwards.
  286. The default, :class:`~flask.json.provider.DefaultJSONProvider`,
  287. uses Python's built-in :mod:`json` library. A different provider
  288. can use a different JSON library.
  289. .. versionadded:: 2.2
  290. """
  291. #: A list of functions that are called by
  292. #: :meth:`handle_url_build_error` when :meth:`.url_for` raises a
  293. #: :exc:`~werkzeug.routing.BuildError`. Each function is called
  294. #: with ``error``, ``endpoint`` and ``values``. If a function
  295. #: returns ``None`` or raises a ``BuildError``, it is skipped.
  296. #: Otherwise, its return value is returned by ``url_for``.
  297. #:
  298. #: .. versionadded:: 0.9
  299. self.url_build_error_handlers: list[
  300. t.Callable[[Exception, str, dict[str, t.Any]], str]
  301. ] = []
  302. #: A list of functions that are called when the application context
  303. #: is destroyed. Since the application context is also torn down
  304. #: if the request ends this is the place to store code that disconnects
  305. #: from databases.
  306. #:
  307. #: .. versionadded:: 0.9
  308. self.teardown_appcontext_funcs: list[ft.TeardownCallable] = []
  309. #: A list of shell context processor functions that should be run
  310. #: when a shell context is created.
  311. #:
  312. #: .. versionadded:: 0.11
  313. self.shell_context_processors: list[ft.ShellContextProcessorCallable] = []
  314. #: Maps registered blueprint names to blueprint objects. The
  315. #: dict retains the order the blueprints were registered in.
  316. #: Blueprints can be registered multiple times, this dict does
  317. #: not track how often they were attached.
  318. #:
  319. #: .. versionadded:: 0.7
  320. self.blueprints: dict[str, Blueprint] = {}
  321. #: a place where extensions can store application specific state. For
  322. #: example this is where an extension could store database engines and
  323. #: similar things.
  324. #:
  325. #: The key must match the name of the extension module. For example in
  326. #: case of a "Flask-Foo" extension in `flask_foo`, the key would be
  327. #: ``'foo'``.
  328. #:
  329. #: .. versionadded:: 0.7
  330. self.extensions: dict = {}
  331. #: The :class:`~werkzeug.routing.Map` for this instance. You can use
  332. #: this to change the routing converters after the class was created
  333. #: but before any routes are connected. Example::
  334. #:
  335. #: from werkzeug.routing import BaseConverter
  336. #:
  337. #: class ListConverter(BaseConverter):
  338. #: def to_python(self, value):
  339. #: return value.split(',')
  340. #: def to_url(self, values):
  341. #: return ','.join(super(ListConverter, self).to_url(value)
  342. #: for value in values)
  343. #:
  344. #: app = Flask(__name__)
  345. #: app.url_map.converters['list'] = ListConverter
  346. self.url_map = self.url_map_class(host_matching=host_matching)
  347. self.subdomain_matching = subdomain_matching
  348. # tracks internally if the application already handled at least one
  349. # request.
  350. self._got_first_request = False
  351. # Set the name of the Click group in case someone wants to add
  352. # the app's commands to another CLI tool.
  353. self.cli.name = self.name
  354. def _check_setup_finished(self, f_name: str) -> None:
  355. if self._got_first_request:
  356. raise AssertionError(
  357. f"The setup method '{f_name}' can no longer be called"
  358. " on the application. It has already handled its first"
  359. " request, any changes will not be applied"
  360. " consistently.\n"
  361. "Make sure all imports, decorators, functions, etc."
  362. " needed to set up the application are done before"
  363. " running it."
  364. )
  365. @cached_property
  366. def name(self) -> str: # type: ignore
  367. """The name of the application. This is usually the import name
  368. with the difference that it's guessed from the run file if the
  369. import name is main. This name is used as a display name when
  370. Flask needs the name of the application. It can be set and overridden
  371. to change the value.
  372. .. versionadded:: 0.8
  373. """
  374. if self.import_name == "__main__":
  375. fn = getattr(sys.modules["__main__"], "__file__", None)
  376. if fn is None:
  377. return "__main__"
  378. return os.path.splitext(os.path.basename(fn))[0]
  379. return self.import_name
  380. @cached_property
  381. def logger(self) -> logging.Logger:
  382. """A standard Python :class:`~logging.Logger` for the app, with
  383. the same name as :attr:`name`.
  384. In debug mode, the logger's :attr:`~logging.Logger.level` will
  385. be set to :data:`~logging.DEBUG`.
  386. If there are no handlers configured, a default handler will be
  387. added. See :doc:`/logging` for more information.
  388. .. versionchanged:: 1.1.0
  389. The logger takes the same name as :attr:`name` rather than
  390. hard-coding ``"flask.app"``.
  391. .. versionchanged:: 1.0.0
  392. Behavior was simplified. The logger is always named
  393. ``"flask.app"``. The level is only set during configuration,
  394. it doesn't check ``app.debug`` each time. Only one format is
  395. used, not different ones depending on ``app.debug``. No
  396. handlers are removed, and a handler is only added if no
  397. handlers are already configured.
  398. .. versionadded:: 0.3
  399. """
  400. return create_logger(self)
  401. @cached_property
  402. def jinja_env(self) -> Environment:
  403. """The Jinja environment used to load templates.
  404. The environment is created the first time this property is
  405. accessed. Changing :attr:`jinja_options` after that will have no
  406. effect.
  407. """
  408. return self.create_jinja_environment()
  409. def create_jinja_environment(self) -> Environment:
  410. raise NotImplementedError()
  411. def make_config(self, instance_relative: bool = False) -> Config:
  412. """Used to create the config attribute by the Flask constructor.
  413. The `instance_relative` parameter is passed in from the constructor
  414. of Flask (there named `instance_relative_config`) and indicates if
  415. the config should be relative to the instance path or the root path
  416. of the application.
  417. .. versionadded:: 0.8
  418. """
  419. root_path = self.root_path
  420. if instance_relative:
  421. root_path = self.instance_path
  422. defaults = dict(self.default_config)
  423. defaults["DEBUG"] = get_debug_flag()
  424. return self.config_class(root_path, defaults)
  425. def make_aborter(self) -> Aborter:
  426. """Create the object to assign to :attr:`aborter`. That object
  427. is called by :func:`flask.abort` to raise HTTP errors, and can
  428. be called directly as well.
  429. By default, this creates an instance of :attr:`aborter_class`,
  430. which defaults to :class:`werkzeug.exceptions.Aborter`.
  431. .. versionadded:: 2.2
  432. """
  433. return self.aborter_class()
  434. def auto_find_instance_path(self) -> str:
  435. """Tries to locate the instance path if it was not provided to the
  436. constructor of the application class. It will basically calculate
  437. the path to a folder named ``instance`` next to your main file or
  438. the package.
  439. .. versionadded:: 0.8
  440. """
  441. prefix, package_path = find_package(self.import_name)
  442. if prefix is None:
  443. return os.path.join(package_path, "instance")
  444. return os.path.join(prefix, "var", f"{self.name}-instance")
  445. def create_global_jinja_loader(self) -> DispatchingJinjaLoader:
  446. """Creates the loader for the Jinja2 environment. Can be used to
  447. override just the loader and keeping the rest unchanged. It's
  448. discouraged to override this function. Instead one should override
  449. the :meth:`jinja_loader` function instead.
  450. The global loader dispatches between the loaders of the application
  451. and the individual blueprints.
  452. .. versionadded:: 0.7
  453. """
  454. return DispatchingJinjaLoader(self)
  455. def select_jinja_autoescape(self, filename: str) -> bool:
  456. """Returns ``True`` if autoescaping should be active for the given
  457. template name. If no template name is given, returns `True`.
  458. .. versionchanged:: 2.2
  459. Autoescaping is now enabled by default for ``.svg`` files.
  460. .. versionadded:: 0.5
  461. """
  462. if filename is None:
  463. return True
  464. return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))
  465. @property
  466. def debug(self) -> bool:
  467. """Whether debug mode is enabled. When using ``flask run`` to start the
  468. development server, an interactive debugger will be shown for unhandled
  469. exceptions, and the server will be reloaded when code changes. This maps to the
  470. :data:`DEBUG` config key. It may not behave as expected if set late.
  471. **Do not enable debug mode when deploying in production.**
  472. Default: ``False``
  473. """
  474. return self.config["DEBUG"]
  475. @debug.setter
  476. def debug(self, value: bool) -> None:
  477. self.config["DEBUG"] = value
  478. if self.config["TEMPLATES_AUTO_RELOAD"] is None:
  479. self.jinja_env.auto_reload = value
  480. @setupmethod
  481. def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:
  482. """Register a :class:`~flask.Blueprint` on the application. Keyword
  483. arguments passed to this method will override the defaults set on the
  484. blueprint.
  485. Calls the blueprint's :meth:`~flask.Blueprint.register` method after
  486. recording the blueprint in the application's :attr:`blueprints`.
  487. :param blueprint: The blueprint to register.
  488. :param url_prefix: Blueprint routes will be prefixed with this.
  489. :param subdomain: Blueprint routes will match on this subdomain.
  490. :param url_defaults: Blueprint routes will use these default values for
  491. view arguments.
  492. :param options: Additional keyword arguments are passed to
  493. :class:`~flask.blueprints.BlueprintSetupState`. They can be
  494. accessed in :meth:`~flask.Blueprint.record` callbacks.
  495. .. versionchanged:: 2.0.1
  496. The ``name`` option can be used to change the (pre-dotted)
  497. name the blueprint is registered with. This allows the same
  498. blueprint to be registered multiple times with unique names
  499. for ``url_for``.
  500. .. versionadded:: 0.7
  501. """
  502. blueprint.register(self, options)
  503. def iter_blueprints(self) -> t.ValuesView[Blueprint]:
  504. """Iterates over all blueprints by the order they were registered.
  505. .. versionadded:: 0.11
  506. """
  507. return self.blueprints.values()
  508. @setupmethod
  509. def add_url_rule(
  510. self,
  511. rule: str,
  512. endpoint: str | None = None,
  513. view_func: ft.RouteCallable | None = None,
  514. provide_automatic_options: bool | None = None,
  515. **options: t.Any,
  516. ) -> None:
  517. if endpoint is None:
  518. endpoint = _endpoint_from_view_func(view_func) # type: ignore
  519. options["endpoint"] = endpoint
  520. methods = options.pop("methods", None)
  521. # if the methods are not given and the view_func object knows its
  522. # methods we can use that instead. If neither exists, we go with
  523. # a tuple of only ``GET`` as default.
  524. if methods is None:
  525. methods = getattr(view_func, "methods", None) or ("GET",)
  526. if isinstance(methods, str):
  527. raise TypeError(
  528. "Allowed methods must be a list of strings, for"
  529. ' example: @app.route(..., methods=["POST"])'
  530. )
  531. methods = {item.upper() for item in methods}
  532. # Methods that should always be added
  533. required_methods = set(getattr(view_func, "required_methods", ()))
  534. # starting with Flask 0.8 the view_func object can disable and
  535. # force-enable the automatic options handling.
  536. if provide_automatic_options is None:
  537. provide_automatic_options = getattr(
  538. view_func, "provide_automatic_options", None
  539. )
  540. if provide_automatic_options is None:
  541. if "OPTIONS" not in methods:
  542. provide_automatic_options = True
  543. required_methods.add("OPTIONS")
  544. else:
  545. provide_automatic_options = False
  546. # Add the required methods now.
  547. methods |= required_methods
  548. rule = self.url_rule_class(rule, methods=methods, **options)
  549. rule.provide_automatic_options = provide_automatic_options # type: ignore
  550. self.url_map.add(rule)
  551. if view_func is not None:
  552. old_func = self.view_functions.get(endpoint)
  553. if old_func is not None and old_func != view_func:
  554. raise AssertionError(
  555. "View function mapping is overwriting an existing"
  556. f" endpoint function: {endpoint}"
  557. )
  558. self.view_functions[endpoint] = view_func
  559. @setupmethod
  560. def template_filter(
  561. self, name: str | None = None
  562. ) -> t.Callable[[T_template_filter], T_template_filter]:
  563. """A decorator that is used to register custom template filter.
  564. You can specify a name for the filter, otherwise the function
  565. name will be used. Example::
  566. @app.template_filter()
  567. def reverse(s):
  568. return s[::-1]
  569. :param name: the optional name of the filter, otherwise the
  570. function name will be used.
  571. """
  572. def decorator(f: T_template_filter) -> T_template_filter:
  573. self.add_template_filter(f, name=name)
  574. return f
  575. return decorator
  576. @setupmethod
  577. def add_template_filter(
  578. self, f: ft.TemplateFilterCallable, name: str | None = None
  579. ) -> None:
  580. """Register a custom template filter. Works exactly like the
  581. :meth:`template_filter` decorator.
  582. :param name: the optional name of the filter, otherwise the
  583. function name will be used.
  584. """
  585. self.jinja_env.filters[name or f.__name__] = f
  586. @setupmethod
  587. def template_test(
  588. self, name: str | None = None
  589. ) -> t.Callable[[T_template_test], T_template_test]:
  590. """A decorator that is used to register custom template test.
  591. You can specify a name for the test, otherwise the function
  592. name will be used. Example::
  593. @app.template_test()
  594. def is_prime(n):
  595. if n == 2:
  596. return True
  597. for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
  598. if n % i == 0:
  599. return False
  600. return True
  601. .. versionadded:: 0.10
  602. :param name: the optional name of the test, otherwise the
  603. function name will be used.
  604. """
  605. def decorator(f: T_template_test) -> T_template_test:
  606. self.add_template_test(f, name=name)
  607. return f
  608. return decorator
  609. @setupmethod
  610. def add_template_test(
  611. self, f: ft.TemplateTestCallable, name: str | None = None
  612. ) -> None:
  613. """Register a custom template test. Works exactly like the
  614. :meth:`template_test` decorator.
  615. .. versionadded:: 0.10
  616. :param name: the optional name of the test, otherwise the
  617. function name will be used.
  618. """
  619. self.jinja_env.tests[name or f.__name__] = f
  620. @setupmethod
  621. def template_global(
  622. self, name: str | None = None
  623. ) -> t.Callable[[T_template_global], T_template_global]:
  624. """A decorator that is used to register a custom template global function.
  625. You can specify a name for the global function, otherwise the function
  626. name will be used. Example::
  627. @app.template_global()
  628. def double(n):
  629. return 2 * n
  630. .. versionadded:: 0.10
  631. :param name: the optional name of the global function, otherwise the
  632. function name will be used.
  633. """
  634. def decorator(f: T_template_global) -> T_template_global:
  635. self.add_template_global(f, name=name)
  636. return f
  637. return decorator
  638. @setupmethod
  639. def add_template_global(
  640. self, f: ft.TemplateGlobalCallable, name: str | None = None
  641. ) -> None:
  642. """Register a custom template global function. Works exactly like the
  643. :meth:`template_global` decorator.
  644. .. versionadded:: 0.10
  645. :param name: the optional name of the global function, otherwise the
  646. function name will be used.
  647. """
  648. self.jinja_env.globals[name or f.__name__] = f
  649. @setupmethod
  650. def teardown_appcontext(self, f: T_teardown) -> T_teardown:
  651. """Registers a function to be called when the application
  652. context is popped. The application context is typically popped
  653. after the request context for each request, at the end of CLI
  654. commands, or after a manually pushed context ends.
  655. .. code-block:: python
  656. with app.app_context():
  657. ...
  658. When the ``with`` block exits (or ``ctx.pop()`` is called), the
  659. teardown functions are called just before the app context is
  660. made inactive. Since a request context typically also manages an
  661. application context it would also be called when you pop a
  662. request context.
  663. When a teardown function was called because of an unhandled
  664. exception it will be passed an error object. If an
  665. :meth:`errorhandler` is registered, it will handle the exception
  666. and the teardown will not receive it.
  667. Teardown functions must avoid raising exceptions. If they
  668. execute code that might fail they must surround that code with a
  669. ``try``/``except`` block and log any errors.
  670. The return values of teardown functions are ignored.
  671. .. versionadded:: 0.9
  672. """
  673. self.teardown_appcontext_funcs.append(f)
  674. return f
  675. @setupmethod
  676. def shell_context_processor(
  677. self, f: T_shell_context_processor
  678. ) -> T_shell_context_processor:
  679. """Registers a shell context processor function.
  680. .. versionadded:: 0.11
  681. """
  682. self.shell_context_processors.append(f)
  683. return f
  684. def _find_error_handler(
  685. self, e: Exception, blueprints: list[str]
  686. ) -> ft.ErrorHandlerCallable | None:
  687. """Return a registered error handler for an exception in this order:
  688. blueprint handler for a specific code, app handler for a specific code,
  689. blueprint handler for an exception class, app handler for an exception
  690. class, or ``None`` if a suitable handler is not found.
  691. """
  692. exc_class, code = self._get_exc_class_and_code(type(e))
  693. names = (*blueprints, None)
  694. for c in (code, None) if code is not None else (None,):
  695. for name in names:
  696. handler_map = self.error_handler_spec[name][c]
  697. if not handler_map:
  698. continue
  699. for cls in exc_class.__mro__:
  700. handler = handler_map.get(cls)
  701. if handler is not None:
  702. return handler
  703. return None
  704. def trap_http_exception(self, e: Exception) -> bool:
  705. """Checks if an HTTP exception should be trapped or not. By default
  706. this will return ``False`` for all exceptions except for a bad request
  707. key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
  708. also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
  709. This is called for all HTTP exceptions raised by a view function.
  710. If it returns ``True`` for any exception the error handler for this
  711. exception is not called and it shows up as regular exception in the
  712. traceback. This is helpful for debugging implicitly raised HTTP
  713. exceptions.
  714. .. versionchanged:: 1.0
  715. Bad request errors are not trapped by default in debug mode.
  716. .. versionadded:: 0.8
  717. """
  718. if self.config["TRAP_HTTP_EXCEPTIONS"]:
  719. return True
  720. trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]
  721. # if unset, trap key errors in debug mode
  722. if (
  723. trap_bad_request is None
  724. and self.debug
  725. and isinstance(e, BadRequestKeyError)
  726. ):
  727. return True
  728. if trap_bad_request:
  729. return isinstance(e, BadRequest)
  730. return False
  731. def should_ignore_error(self, error: BaseException | None) -> bool:
  732. """This is called to figure out if an error should be ignored
  733. or not as far as the teardown system is concerned. If this
  734. function returns ``True`` then the teardown handlers will not be
  735. passed the error.
  736. .. versionadded:: 0.10
  737. """
  738. return False
  739. def redirect(self, location: str, code: int = 302) -> BaseResponse:
  740. """Create a redirect response object.
  741. This is called by :func:`flask.redirect`, and can be called
  742. directly as well.
  743. :param location: The URL to redirect to.
  744. :param code: The status code for the redirect.
  745. .. versionadded:: 2.2
  746. Moved from ``flask.redirect``, which calls this method.
  747. """
  748. return _wz_redirect(
  749. location, code=code, Response=self.response_class # type: ignore[arg-type]
  750. )
  751. def inject_url_defaults(self, endpoint: str, values: dict) -> 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