app.py 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091
  1. import functools
  2. import inspect
  3. import logging
  4. import os
  5. import sys
  6. import typing as t
  7. import weakref
  8. from datetime import timedelta
  9. from itertools import chain
  10. from threading import Lock
  11. from types import TracebackType
  12. from werkzeug.datastructures import Headers
  13. from werkzeug.datastructures import ImmutableDict
  14. from werkzeug.exceptions import BadRequest
  15. from werkzeug.exceptions import BadRequestKeyError
  16. from werkzeug.exceptions import HTTPException
  17. from werkzeug.exceptions import InternalServerError
  18. from werkzeug.routing import BuildError
  19. from werkzeug.routing import Map
  20. from werkzeug.routing import MapAdapter
  21. from werkzeug.routing import RequestRedirect
  22. from werkzeug.routing import RoutingException
  23. from werkzeug.routing import Rule
  24. from werkzeug.wrappers import Response as BaseResponse
  25. from . import cli
  26. from . import json
  27. from . import typing as ft
  28. from .config import Config
  29. from .config import ConfigAttribute
  30. from .ctx import _AppCtxGlobals
  31. from .ctx import AppContext
  32. from .ctx import RequestContext
  33. from .globals import _request_ctx_stack
  34. from .globals import g
  35. from .globals import request
  36. from .globals import session
  37. from .helpers import _split_blueprint_path
  38. from .helpers import get_debug_flag
  39. from .helpers import get_env
  40. from .helpers import get_flashed_messages
  41. from .helpers import get_load_dotenv
  42. from .helpers import locked_cached_property
  43. from .helpers import url_for
  44. from .json import jsonify
  45. from .logging import create_logger
  46. from .scaffold import _endpoint_from_view_func
  47. from .scaffold import _sentinel
  48. from .scaffold import find_package
  49. from .scaffold import Scaffold
  50. from .scaffold import setupmethod
  51. from .sessions import SecureCookieSessionInterface
  52. from .sessions import SessionInterface
  53. from .signals import appcontext_tearing_down
  54. from .signals import got_request_exception
  55. from .signals import request_finished
  56. from .signals import request_started
  57. from .signals import request_tearing_down
  58. from .templating import DispatchingJinjaLoader
  59. from .templating import Environment
  60. from .wrappers import Request
  61. from .wrappers import Response
  62. if t.TYPE_CHECKING:
  63. import typing_extensions as te
  64. from .blueprints import Blueprint
  65. from .testing import FlaskClient
  66. from .testing import FlaskCliRunner
  67. if sys.version_info >= (3, 8):
  68. iscoroutinefunction = inspect.iscoroutinefunction
  69. else:
  70. def iscoroutinefunction(func: t.Any) -> bool:
  71. while inspect.ismethod(func):
  72. func = func.__func__
  73. while isinstance(func, functools.partial):
  74. func = func.func
  75. return inspect.iscoroutinefunction(func)
  76. def _make_timedelta(value: t.Optional[timedelta]) -> t.Optional[timedelta]:
  77. if value is None or isinstance(value, timedelta):
  78. return value
  79. return timedelta(seconds=value)
  80. class Flask(Scaffold):
  81. """The flask object implements a WSGI application and acts as the central
  82. object. It is passed the name of the module or package of the
  83. application. Once it is created it will act as a central registry for
  84. the view functions, the URL rules, template configuration and much more.
  85. The name of the package is used to resolve resources from inside the
  86. package or the folder the module is contained in depending on if the
  87. package parameter resolves to an actual python package (a folder with
  88. an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
  89. For more information about resource loading, see :func:`open_resource`.
  90. Usually you create a :class:`Flask` instance in your main module or
  91. in the :file:`__init__.py` file of your package like this::
  92. from flask import Flask
  93. app = Flask(__name__)
  94. .. admonition:: About the First Parameter
  95. The idea of the first parameter is to give Flask an idea of what
  96. belongs to your application. This name is used to find resources
  97. on the filesystem, can be used by extensions to improve debugging
  98. information and a lot more.
  99. So it's important what you provide there. If you are using a single
  100. module, `__name__` is always the correct value. If you however are
  101. using a package, it's usually recommended to hardcode the name of
  102. your package there.
  103. For example if your application is defined in :file:`yourapplication/app.py`
  104. you should create it with one of the two versions below::
  105. app = Flask('yourapplication')
  106. app = Flask(__name__.split('.')[0])
  107. Why is that? The application will work even with `__name__`, thanks
  108. to how resources are looked up. However it will make debugging more
  109. painful. Certain extensions can make assumptions based on the
  110. import name of your application. For example the Flask-SQLAlchemy
  111. extension will look for the code in your application that triggered
  112. an SQL query in debug mode. If the import name is not properly set
  113. up, that debugging information is lost. (For example it would only
  114. pick up SQL queries in `yourapplication.app` and not
  115. `yourapplication.views.frontend`)
  116. .. versionadded:: 0.7
  117. The `static_url_path`, `static_folder`, and `template_folder`
  118. parameters were added.
  119. .. versionadded:: 0.8
  120. The `instance_path` and `instance_relative_config` parameters were
  121. added.
  122. .. versionadded:: 0.11
  123. The `root_path` parameter was added.
  124. .. versionadded:: 1.0
  125. The ``host_matching`` and ``static_host`` parameters were added.
  126. .. versionadded:: 1.0
  127. The ``subdomain_matching`` parameter was added. Subdomain
  128. matching needs to be enabled manually now. Setting
  129. :data:`SERVER_NAME` does not implicitly enable it.
  130. :param import_name: the name of the application package
  131. :param static_url_path: can be used to specify a different path for the
  132. static files on the web. Defaults to the name
  133. of the `static_folder` folder.
  134. :param static_folder: The folder with static files that is served at
  135. ``static_url_path``. Relative to the application ``root_path``
  136. or an absolute path. Defaults to ``'static'``.
  137. :param static_host: the host to use when adding the static route.
  138. Defaults to None. Required when using ``host_matching=True``
  139. with a ``static_folder`` configured.
  140. :param host_matching: set ``url_map.host_matching`` attribute.
  141. Defaults to False.
  142. :param subdomain_matching: consider the subdomain relative to
  143. :data:`SERVER_NAME` when matching routes. Defaults to False.
  144. :param template_folder: the folder that contains the templates that should
  145. be used by the application. Defaults to
  146. ``'templates'`` folder in the root path of the
  147. application.
  148. :param instance_path: An alternative instance path for the application.
  149. By default the folder ``'instance'`` next to the
  150. package or module is assumed to be the instance
  151. path.
  152. :param instance_relative_config: if set to ``True`` relative filenames
  153. for loading the config are assumed to
  154. be relative to the instance path instead
  155. of the application root.
  156. :param root_path: The path to the root of the application files.
  157. This should only be set manually when it can't be detected
  158. automatically, such as for namespace packages.
  159. """
  160. #: The class that is used for request objects. See :class:`~flask.Request`
  161. #: for more information.
  162. request_class = Request
  163. #: The class that is used for response objects. See
  164. #: :class:`~flask.Response` for more information.
  165. response_class = Response
  166. #: The class that is used for the Jinja environment.
  167. #:
  168. #: .. versionadded:: 0.11
  169. jinja_environment = Environment
  170. #: The class that is used for the :data:`~flask.g` instance.
  171. #:
  172. #: Example use cases for a custom class:
  173. #:
  174. #: 1. Store arbitrary attributes on flask.g.
  175. #: 2. Add a property for lazy per-request database connectors.
  176. #: 3. Return None instead of AttributeError on unexpected attributes.
  177. #: 4. Raise exception if an unexpected attr is set, a "controlled" flask.g.
  178. #:
  179. #: In Flask 0.9 this property was called `request_globals_class` but it
  180. #: was changed in 0.10 to :attr:`app_ctx_globals_class` because the
  181. #: flask.g object is now application context scoped.
  182. #:
  183. #: .. versionadded:: 0.10
  184. app_ctx_globals_class = _AppCtxGlobals
  185. #: The class that is used for the ``config`` attribute of this app.
  186. #: Defaults to :class:`~flask.Config`.
  187. #:
  188. #: Example use cases for a custom class:
  189. #:
  190. #: 1. Default values for certain config options.
  191. #: 2. Access to config values through attributes in addition to keys.
  192. #:
  193. #: .. versionadded:: 0.11
  194. config_class = Config
  195. #: The testing flag. Set this to ``True`` to enable the test mode of
  196. #: Flask extensions (and in the future probably also Flask itself).
  197. #: For example this might activate test helpers that have an
  198. #: additional runtime cost which should not be enabled by default.
  199. #:
  200. #: If this is enabled and PROPAGATE_EXCEPTIONS is not changed from the
  201. #: default it's implicitly enabled.
  202. #:
  203. #: This attribute can also be configured from the config with the
  204. #: ``TESTING`` configuration key. Defaults to ``False``.
  205. testing = ConfigAttribute("TESTING")
  206. #: If a secret key is set, cryptographic components can use this to
  207. #: sign cookies and other things. Set this to a complex random value
  208. #: when you want to use the secure cookie for instance.
  209. #:
  210. #: This attribute can also be configured from the config with the
  211. #: :data:`SECRET_KEY` configuration key. Defaults to ``None``.
  212. secret_key = ConfigAttribute("SECRET_KEY")
  213. #: The secure cookie uses this for the name of the session cookie.
  214. #:
  215. #: This attribute can also be configured from the config with the
  216. #: ``SESSION_COOKIE_NAME`` configuration key. Defaults to ``'session'``
  217. session_cookie_name = ConfigAttribute("SESSION_COOKIE_NAME")
  218. #: A :class:`~datetime.timedelta` which is used to set the expiration
  219. #: date of a permanent session. The default is 31 days which makes a
  220. #: permanent session survive for roughly one month.
  221. #:
  222. #: This attribute can also be configured from the config with the
  223. #: ``PERMANENT_SESSION_LIFETIME`` configuration key. Defaults to
  224. #: ``timedelta(days=31)``
  225. permanent_session_lifetime = ConfigAttribute(
  226. "PERMANENT_SESSION_LIFETIME", get_converter=_make_timedelta
  227. )
  228. #: A :class:`~datetime.timedelta` or number of seconds which is used
  229. #: as the default ``max_age`` for :func:`send_file`. The default is
  230. #: ``None``, which tells the browser to use conditional requests
  231. #: instead of a timed cache.
  232. #:
  233. #: Configured with the :data:`SEND_FILE_MAX_AGE_DEFAULT`
  234. #: configuration key.
  235. #:
  236. #: .. versionchanged:: 2.0
  237. #: Defaults to ``None`` instead of 12 hours.
  238. send_file_max_age_default = ConfigAttribute(
  239. "SEND_FILE_MAX_AGE_DEFAULT", get_converter=_make_timedelta
  240. )
  241. #: Enable this if you want to use the X-Sendfile feature. Keep in
  242. #: mind that the server has to support this. This only affects files
  243. #: sent with the :func:`send_file` method.
  244. #:
  245. #: .. versionadded:: 0.2
  246. #:
  247. #: This attribute can also be configured from the config with the
  248. #: ``USE_X_SENDFILE`` configuration key. Defaults to ``False``.
  249. use_x_sendfile = ConfigAttribute("USE_X_SENDFILE")
  250. #: The JSON encoder class to use. Defaults to :class:`~flask.json.JSONEncoder`.
  251. #:
  252. #: .. versionadded:: 0.10
  253. json_encoder = json.JSONEncoder
  254. #: The JSON decoder class to use. Defaults to :class:`~flask.json.JSONDecoder`.
  255. #:
  256. #: .. versionadded:: 0.10
  257. json_decoder = json.JSONDecoder
  258. #: Options that are passed to the Jinja environment in
  259. #: :meth:`create_jinja_environment`. Changing these options after
  260. #: the environment is created (accessing :attr:`jinja_env`) will
  261. #: have no effect.
  262. #:
  263. #: .. versionchanged:: 1.1.0
  264. #: This is a ``dict`` instead of an ``ImmutableDict`` to allow
  265. #: easier configuration.
  266. #:
  267. jinja_options: dict = {}
  268. #: Default configuration parameters.
  269. default_config = ImmutableDict(
  270. {
  271. "ENV": None,
  272. "DEBUG": None,
  273. "TESTING": False,
  274. "PROPAGATE_EXCEPTIONS": None,
  275. "PRESERVE_CONTEXT_ON_EXCEPTION": None,
  276. "SECRET_KEY": None,
  277. "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
  278. "USE_X_SENDFILE": False,
  279. "SERVER_NAME": None,
  280. "APPLICATION_ROOT": "/",
  281. "SESSION_COOKIE_NAME": "session",
  282. "SESSION_COOKIE_DOMAIN": None,
  283. "SESSION_COOKIE_PATH": None,
  284. "SESSION_COOKIE_HTTPONLY": True,
  285. "SESSION_COOKIE_SECURE": False,
  286. "SESSION_COOKIE_SAMESITE": None,
  287. "SESSION_REFRESH_EACH_REQUEST": True,
  288. "MAX_CONTENT_LENGTH": None,
  289. "SEND_FILE_MAX_AGE_DEFAULT": None,
  290. "TRAP_BAD_REQUEST_ERRORS": None,
  291. "TRAP_HTTP_EXCEPTIONS": False,
  292. "EXPLAIN_TEMPLATE_LOADING": False,
  293. "PREFERRED_URL_SCHEME": "http",
  294. "JSON_AS_ASCII": True,
  295. "JSON_SORT_KEYS": True,
  296. "JSONIFY_PRETTYPRINT_REGULAR": False,
  297. "JSONIFY_MIMETYPE": "application/json",
  298. "TEMPLATES_AUTO_RELOAD": None,
  299. "MAX_COOKIE_SIZE": 4093,
  300. }
  301. )
  302. #: The rule object to use for URL rules created. This is used by
  303. #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.
  304. #:
  305. #: .. versionadded:: 0.7
  306. url_rule_class = Rule
  307. #: The map object to use for storing the URL rules and routing
  308. #: configuration parameters. Defaults to :class:`werkzeug.routing.Map`.
  309. #:
  310. #: .. versionadded:: 1.1.0
  311. url_map_class = Map
  312. #: The :meth:`test_client` method creates an instance of this test
  313. #: client class. Defaults to :class:`~flask.testing.FlaskClient`.
  314. #:
  315. #: .. versionadded:: 0.7
  316. test_client_class: t.Optional[t.Type["FlaskClient"]] = None
  317. #: The :class:`~click.testing.CliRunner` subclass, by default
  318. #: :class:`~flask.testing.FlaskCliRunner` that is used by
  319. #: :meth:`test_cli_runner`. Its ``__init__`` method should take a
  320. #: Flask app object as the first argument.
  321. #:
  322. #: .. versionadded:: 1.0
  323. test_cli_runner_class: t.Optional[t.Type["FlaskCliRunner"]] = None
  324. #: the session interface to use. By default an instance of
  325. #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.
  326. #:
  327. #: .. versionadded:: 0.8
  328. session_interface: SessionInterface = SecureCookieSessionInterface()
  329. def __init__(
  330. self,
  331. import_name: str,
  332. static_url_path: t.Optional[str] = None,
  333. static_folder: t.Optional[t.Union[str, os.PathLike]] = "static",
  334. static_host: t.Optional[str] = None,
  335. host_matching: bool = False,
  336. subdomain_matching: bool = False,
  337. template_folder: t.Optional[str] = "templates",
  338. instance_path: t.Optional[str] = None,
  339. instance_relative_config: bool = False,
  340. root_path: t.Optional[str] = None,
  341. ):
  342. super().__init__(
  343. import_name=import_name,
  344. static_folder=static_folder,
  345. static_url_path=static_url_path,
  346. template_folder=template_folder,
  347. root_path=root_path,
  348. )
  349. if instance_path is None:
  350. instance_path = self.auto_find_instance_path()
  351. elif not os.path.isabs(instance_path):
  352. raise ValueError(
  353. "If an instance path is provided it must be absolute."
  354. " A relative path was given instead."
  355. )
  356. #: Holds the path to the instance folder.
  357. #:
  358. #: .. versionadded:: 0.8
  359. self.instance_path = instance_path
  360. #: The configuration dictionary as :class:`Config`. This behaves
  361. #: exactly like a regular dictionary but supports additional methods
  362. #: to load a config from files.
  363. self.config = self.make_config(instance_relative_config)
  364. #: A list of functions that are called when :meth:`url_for` raises a
  365. #: :exc:`~werkzeug.routing.BuildError`. Each function registered here
  366. #: is called with `error`, `endpoint` and `values`. If a function
  367. #: returns ``None`` or raises a :exc:`BuildError` the next function is
  368. #: tried.
  369. #:
  370. #: .. versionadded:: 0.9
  371. self.url_build_error_handlers: t.List[
  372. t.Callable[[Exception, str, dict], str]
  373. ] = []
  374. #: A list of functions that will be called at the beginning of the
  375. #: first request to this instance. To register a function, use the
  376. #: :meth:`before_first_request` decorator.
  377. #:
  378. #: .. versionadded:: 0.8
  379. self.before_first_request_funcs: t.List[ft.BeforeFirstRequestCallable] = []
  380. #: A list of functions that are called when the application context
  381. #: is destroyed. Since the application context is also torn down
  382. #: if the request ends this is the place to store code that disconnects
  383. #: from databases.
  384. #:
  385. #: .. versionadded:: 0.9
  386. self.teardown_appcontext_funcs: t.List[ft.TeardownCallable] = []
  387. #: A list of shell context processor functions that should be run
  388. #: when a shell context is created.
  389. #:
  390. #: .. versionadded:: 0.11
  391. self.shell_context_processors: t.List[t.Callable[[], t.Dict[str, t.Any]]] = []
  392. #: Maps registered blueprint names to blueprint objects. The
  393. #: dict retains the order the blueprints were registered in.
  394. #: Blueprints can be registered multiple times, this dict does
  395. #: not track how often they were attached.
  396. #:
  397. #: .. versionadded:: 0.7
  398. self.blueprints: t.Dict[str, "Blueprint"] = {}
  399. #: a place where extensions can store application specific state. For
  400. #: example this is where an extension could store database engines and
  401. #: similar things.
  402. #:
  403. #: The key must match the name of the extension module. For example in
  404. #: case of a "Flask-Foo" extension in `flask_foo`, the key would be
  405. #: ``'foo'``.
  406. #:
  407. #: .. versionadded:: 0.7
  408. self.extensions: dict = {}
  409. #: The :class:`~werkzeug.routing.Map` for this instance. You can use
  410. #: this to change the routing converters after the class was created
  411. #: but before any routes are connected. Example::
  412. #:
  413. #: from werkzeug.routing import BaseConverter
  414. #:
  415. #: class ListConverter(BaseConverter):
  416. #: def to_python(self, value):
  417. #: return value.split(',')
  418. #: def to_url(self, values):
  419. #: return ','.join(super(ListConverter, self).to_url(value)
  420. #: for value in values)
  421. #:
  422. #: app = Flask(__name__)
  423. #: app.url_map.converters['list'] = ListConverter
  424. self.url_map = self.url_map_class()
  425. self.url_map.host_matching = host_matching
  426. self.subdomain_matching = subdomain_matching
  427. # tracks internally if the application already handled at least one
  428. # request.
  429. self._got_first_request = False
  430. self._before_request_lock = Lock()
  431. # Add a static route using the provided static_url_path, static_host,
  432. # and static_folder if there is a configured static_folder.
  433. # Note we do this without checking if static_folder exists.
  434. # For one, it might be created while the server is running (e.g. during
  435. # development). Also, Google App Engine stores static files somewhere
  436. if self.has_static_folder:
  437. assert (
  438. bool(static_host) == host_matching
  439. ), "Invalid static_host/host_matching combination"
  440. # Use a weakref to avoid creating a reference cycle between the app
  441. # and the view function (see #3761).
  442. self_ref = weakref.ref(self)
  443. self.add_url_rule(
  444. f"{self.static_url_path}/<path:filename>",
  445. endpoint="static",
  446. host=static_host,
  447. view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950
  448. )
  449. # Set the name of the Click group in case someone wants to add
  450. # the app's commands to another CLI tool.
  451. self.cli.name = self.name
  452. def _is_setup_finished(self) -> bool:
  453. return self.debug and self._got_first_request
  454. @locked_cached_property
  455. def name(self) -> str: # type: ignore
  456. """The name of the application. This is usually the import name
  457. with the difference that it's guessed from the run file if the
  458. import name is main. This name is used as a display name when
  459. Flask needs the name of the application. It can be set and overridden
  460. to change the value.
  461. .. versionadded:: 0.8
  462. """
  463. if self.import_name == "__main__":
  464. fn = getattr(sys.modules["__main__"], "__file__", None)
  465. if fn is None:
  466. return "__main__"
  467. return os.path.splitext(os.path.basename(fn))[0]
  468. return self.import_name
  469. @property
  470. def propagate_exceptions(self) -> bool:
  471. """Returns the value of the ``PROPAGATE_EXCEPTIONS`` configuration
  472. value in case it's set, otherwise a sensible default is returned.
  473. .. versionadded:: 0.7
  474. """
  475. rv = self.config["PROPAGATE_EXCEPTIONS"]
  476. if rv is not None:
  477. return rv
  478. return self.testing or self.debug
  479. @property
  480. def preserve_context_on_exception(self) -> bool:
  481. """Returns the value of the ``PRESERVE_CONTEXT_ON_EXCEPTION``
  482. configuration value in case it's set, otherwise a sensible default
  483. is returned.
  484. .. versionadded:: 0.7
  485. """
  486. rv = self.config["PRESERVE_CONTEXT_ON_EXCEPTION"]
  487. if rv is not None:
  488. return rv
  489. return self.debug
  490. @locked_cached_property
  491. def logger(self) -> logging.Logger:
  492. """A standard Python :class:`~logging.Logger` for the app, with
  493. the same name as :attr:`name`.
  494. In debug mode, the logger's :attr:`~logging.Logger.level` will
  495. be set to :data:`~logging.DEBUG`.
  496. If there are no handlers configured, a default handler will be
  497. added. See :doc:`/logging` for more information.
  498. .. versionchanged:: 1.1.0
  499. The logger takes the same name as :attr:`name` rather than
  500. hard-coding ``"flask.app"``.
  501. .. versionchanged:: 1.0.0
  502. Behavior was simplified. The logger is always named
  503. ``"flask.app"``. The level is only set during configuration,
  504. it doesn't check ``app.debug`` each time. Only one format is
  505. used, not different ones depending on ``app.debug``. No
  506. handlers are removed, and a handler is only added if no
  507. handlers are already configured.
  508. .. versionadded:: 0.3
  509. """
  510. return create_logger(self)
  511. @locked_cached_property
  512. def jinja_env(self) -> Environment:
  513. """The Jinja environment used to load templates.
  514. The environment is created the first time this property is
  515. accessed. Changing :attr:`jinja_options` after that will have no
  516. effect.
  517. """
  518. return self.create_jinja_environment()
  519. @property
  520. def got_first_request(self) -> bool:
  521. """This attribute is set to ``True`` if the application started
  522. handling the first request.
  523. .. versionadded:: 0.8
  524. """
  525. return self._got_first_request
  526. def make_config(self, instance_relative: bool = False) -> Config:
  527. """Used to create the config attribute by the Flask constructor.
  528. The `instance_relative` parameter is passed in from the constructor
  529. of Flask (there named `instance_relative_config`) and indicates if
  530. the config should be relative to the instance path or the root path
  531. of the application.
  532. .. versionadded:: 0.8
  533. """
  534. root_path = self.root_path
  535. if instance_relative:
  536. root_path = self.instance_path
  537. defaults = dict(self.default_config)
  538. defaults["ENV"] = get_env()
  539. defaults["DEBUG"] = get_debug_flag()
  540. return self.config_class(root_path, defaults)
  541. def auto_find_instance_path(self) -> str:
  542. """Tries to locate the instance path if it was not provided to the
  543. constructor of the application class. It will basically calculate
  544. the path to a folder named ``instance`` next to your main file or
  545. the package.
  546. .. versionadded:: 0.8
  547. """
  548. prefix, package_path = find_package(self.import_name)
  549. if prefix is None:
  550. return os.path.join(package_path, "instance")
  551. return os.path.join(prefix, "var", f"{self.name}-instance")
  552. def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
  553. """Opens a resource from the application's instance folder
  554. (:attr:`instance_path`). Otherwise works like
  555. :meth:`open_resource`. Instance resources can also be opened for
  556. writing.
  557. :param resource: the name of the resource. To access resources within
  558. subfolders use forward slashes as separator.
  559. :param mode: resource file opening mode, default is 'rb'.
  560. """
  561. return open(os.path.join(self.instance_path, resource), mode)
  562. @property
  563. def templates_auto_reload(self) -> bool:
  564. """Reload templates when they are changed. Used by
  565. :meth:`create_jinja_environment`.
  566. This attribute can be configured with :data:`TEMPLATES_AUTO_RELOAD`. If
  567. not set, it will be enabled in debug mode.
  568. .. versionadded:: 1.0
  569. This property was added but the underlying config and behavior
  570. already existed.
  571. """
  572. rv = self.config["TEMPLATES_AUTO_RELOAD"]
  573. return rv if rv is not None else self.debug
  574. @templates_auto_reload.setter
  575. def templates_auto_reload(self, value: bool) -> None:
  576. self.config["TEMPLATES_AUTO_RELOAD"] = value
  577. def create_jinja_environment(self) -> Environment:
  578. """Create the Jinja environment based on :attr:`jinja_options`
  579. and the various Jinja-related methods of the app. Changing
  580. :attr:`jinja_options` after this will have no effect. Also adds
  581. Flask-related globals and filters to the environment.
  582. .. versionchanged:: 0.11
  583. ``Environment.auto_reload`` set in accordance with
  584. ``TEMPLATES_AUTO_RELOAD`` configuration option.
  585. .. versionadded:: 0.5
  586. """
  587. options = dict(self.jinja_options)
  588. if "autoescape" not in options:
  589. options["autoescape"] = self.select_jinja_autoescape
  590. if "auto_reload" not in options:
  591. options["auto_reload"] = self.templates_auto_reload
  592. rv = self.jinja_environment(self, **options)
  593. rv.globals.update(
  594. url_for=url_for,
  595. get_flashed_messages=get_flashed_messages,
  596. config=self.config,
  597. # request, session and g are normally added with the
  598. # context processor for efficiency reasons but for imported
  599. # templates we also want the proxies in there.
  600. request=request,
  601. session=session,
  602. g=g,
  603. )
  604. rv.policies["json.dumps_function"] = json.dumps
  605. return rv
  606. def create_global_jinja_loader(self) -> DispatchingJinjaLoader:
  607. """Creates the loader for the Jinja2 environment. Can be used to
  608. override just the loader and keeping the rest unchanged. It's
  609. discouraged to override this function. Instead one should override
  610. the :meth:`jinja_loader` function instead.
  611. The global loader dispatches between the loaders of the application
  612. and the individual blueprints.
  613. .. versionadded:: 0.7
  614. """
  615. return DispatchingJinjaLoader(self)
  616. def select_jinja_autoescape(self, filename: str) -> bool:
  617. """Returns ``True`` if autoescaping should be active for the given
  618. template name. If no template name is given, returns `True`.
  619. .. versionadded:: 0.5
  620. """
  621. if filename is None:
  622. return True
  623. return filename.endswith((".html", ".htm", ".xml", ".xhtml"))
  624. def update_template_context(self, context: dict) -> None:
  625. """Update the template context with some commonly used variables.
  626. This injects request, session, config and g into the template
  627. context as well as everything template context processors want
  628. to inject. Note that the as of Flask 0.6, the original values
  629. in the context will not be overridden if a context processor
  630. decides to return a value with the same key.
  631. :param context: the context as a dictionary that is updated in place
  632. to add extra variables.
  633. """
  634. names: t.Iterable[t.Optional[str]] = (None,)
  635. # A template may be rendered outside a request context.
  636. if request:
  637. names = chain(names, reversed(request.blueprints))
  638. # The values passed to render_template take precedence. Keep a
  639. # copy to re-apply after all context functions.
  640. orig_ctx = context.copy()
  641. for name in names:
  642. if name in self.template_context_processors:
  643. for func in self.template_context_processors[name]:
  644. context.update(func())
  645. context.update(orig_ctx)
  646. def make_shell_context(self) -> dict:
  647. """Returns the shell context for an interactive shell for this
  648. application. This runs all the registered shell context
  649. processors.
  650. .. versionadded:: 0.11
  651. """
  652. rv = {"app": self, "g": g}
  653. for processor in self.shell_context_processors:
  654. rv.update(processor())
  655. return rv
  656. #: What environment the app is running in. Flask and extensions may
  657. #: enable behaviors based on the environment, such as enabling debug
  658. #: mode. This maps to the :data:`ENV` config key. This is set by the
  659. #: :envvar:`FLASK_ENV` environment variable and may not behave as
  660. #: expected if set in code.
  661. #:
  662. #: **Do not enable development when deploying in production.**
  663. #:
  664. #: Default: ``'production'``
  665. env = ConfigAttribute("ENV")
  666. @property
  667. def debug(self) -> bool:
  668. """Whether debug mode is enabled. When using ``flask run`` to start
  669. the development server, an interactive debugger will be shown for
  670. unhandled exceptions, and the server will be reloaded when code
  671. changes. This maps to the :data:`DEBUG` config key. This is
  672. enabled when :attr:`env` is ``'development'`` and is overridden
  673. by the ``FLASK_DEBUG`` environment variable. It may not behave as
  674. expected if set in code.
  675. **Do not enable debug mode when deploying in production.**
  676. Default: ``True`` if :attr:`env` is ``'development'``, or
  677. ``False`` otherwise.
  678. """
  679. return self.config["DEBUG"]
  680. @debug.setter
  681. def debug(self, value: bool) -> None:
  682. self.config["DEBUG"] = value
  683. self.jinja_env.auto_reload = self.templates_auto_reload
  684. def run(
  685. self,
  686. host: t.Optional[str] = None,
  687. port: t.Optional[int] = None,
  688. debug: t.Optional[bool] = None,
  689. load_dotenv: bool = True,
  690. **options: t.Any,
  691. ) -> None:
  692. """Runs the application on a local development server.
  693. Do not use ``run()`` in a production setting. It is not intended to
  694. meet security and performance requirements for a production server.
  695. Instead, see :doc:`/deploying/index` for WSGI server recommendations.
  696. If the :attr:`debug` flag is set the server will automatically reload
  697. for code changes and show a debugger in case an exception happened.
  698. If you want to run the application in debug mode, but disable the
  699. code execution on the interactive debugger, you can pass
  700. ``use_evalex=False`` as parameter. This will keep the debugger's
  701. traceback screen active, but disable code execution.
  702. It is not recommended to use this function for development with
  703. automatic reloading as this is badly supported. Instead you should
  704. be using the :command:`flask` command line script's ``run`` support.
  705. .. admonition:: Keep in Mind
  706. Flask will suppress any server error with a generic error page
  707. unless it is in debug mode. As such to enable just the
  708. interactive debugger without the code reloading, you have to
  709. invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
  710. Setting ``use_debugger`` to ``True`` without being in debug mode
  711. won't catch any exceptions because there won't be any to
  712. catch.
  713. :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
  714. have the server available externally as well. Defaults to
  715. ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
  716. if present.
  717. :param port: the port of the webserver. Defaults to ``5000`` or the
  718. port defined in the ``SERVER_NAME`` config variable if present.
  719. :param debug: if given, enable or disable debug mode. See
  720. :attr:`debug`.
  721. :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
  722. files to set environment variables. Will also change the working
  723. directory to the directory containing the first file found.
  724. :param options: the options to be forwarded to the underlying Werkzeug
  725. server. See :func:`werkzeug.serving.run_simple` for more
  726. information.
  727. .. versionchanged:: 1.0
  728. If installed, python-dotenv will be used to load environment
  729. variables from :file:`.env` and :file:`.flaskenv` files.
  730. If set, the :envvar:`FLASK_ENV` and :envvar:`FLASK_DEBUG`
  731. environment variables will override :attr:`env` and
  732. :attr:`debug`.
  733. Threaded mode is enabled by default.
  734. .. versionchanged:: 0.10
  735. The default port is now picked from the ``SERVER_NAME``
  736. variable.
  737. """
  738. # Change this into a no-op if the server is invoked from the
  739. # command line. Have a look at cli.py for more information.
  740. if os.environ.get("FLASK_RUN_FROM_CLI") == "true":
  741. from .debughelpers import explain_ignored_app_run
  742. explain_ignored_app_run()
  743. return
  744. if get_load_dotenv(load_dotenv):
  745. cli.load_dotenv()
  746. # if set, let env vars override previous values
  747. if "FLASK_ENV" in os.environ:
  748. self.env = get_env()
  749. self.debug = get_debug_flag()
  750. elif "FLASK_DEBUG" in os.environ:
  751. self.debug = get_debug_flag()
  752. # debug passed to method overrides all other sources
  753. if debug is not None:
  754. self.debug = bool(debug)
  755. server_name = self.config.get("SERVER_NAME")
  756. sn_host = sn_port = None
  757. if server_name:
  758. sn_host, _, sn_port = server_name.partition(":")
  759. if not host:
  760. if sn_host:
  761. host = sn_host
  762. else:
  763. host = "127.0.0.1"
  764. if port or port == 0:
  765. port = int(port)
  766. elif sn_port:
  767. port = int(sn_port)
  768. else:
  769. port = 5000
  770. options.setdefault("use_reloader", self.debug)
  771. options.setdefault("use_debugger", self.debug)
  772. options.setdefault("threaded", True)
  773. cli.show_server_banner(self.env, self.debug, self.name, False)
  774. from werkzeug.serving import run_simple
  775. try:
  776. run_simple(t.cast(str, host), port, self, **options)
  777. finally:
  778. # reset the first request information if the development server
  779. # reset normally. This makes it possible to restart the server
  780. # without reloader and that stuff from an interactive shell.
  781. self._got_first_request = False
  782. def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> "FlaskClient":
  783. """Creates a test client for this application. For information
  784. about unit testing head over to :doc:`/testing`.
  785. Note that if you are testing for assertions or exceptions in your
  786. application code, you must set ``app.testing = True`` in order for the
  787. exceptions to propagate to the test client. Otherwise, the exception
  788. will be handled by the application (not visible to the test client) and
  789. the only indication of an AssertionError or other exception will be a
  790. 500 status code response to the test client. See the :attr:`testing`
  791. attribute. For example::
  792. app.testing = True
  793. client = app.test_client()
  794. The test client can be used in a ``with`` block to defer the closing down
  795. of the context until the end of the ``with`` block. This is useful if
  796. you want to access the context locals for testing::
  797. with app.test_client() as c:
  798. rv = c.get('/?vodka=42')
  799. assert request.args['vodka'] == '42'
  800. Additionally, you may pass optional keyword arguments that will then
  801. be passed to the application's :attr:`test_client_class` constructor.
  802. For example::
  803. from flask.testing import FlaskClient
  804. class CustomClient(FlaskClient):
  805. def __init__(self, *args, **kwargs):
  806. self._authentication = kwargs.pop("authentication")
  807. super(CustomClient,self).__init__( *args, **kwargs)
  808. app.test_client_class = CustomClient
  809. client = app.test_client(authentication='Basic ....')
  810. See :class:`~flask.testing.FlaskClient` for more information.
  811. .. versionchanged:: 0.4
  812. added support for ``with`` block usage for the client.
  813. .. versionadded:: 0.7
  814. The `use_cookies` parameter was added as well as the ability
  815. to override the client to be used by setting the
  816. :attr:`test_client_class` attribute.
  817. .. versionchanged:: 0.11
  818. Added `**kwargs` to support passing additional keyword arguments to
  819. the constructor of :attr:`test_client_class`.
  820. """
  821. cls = self.test_client_class
  822. if cls is None:
  823. from .testing import FlaskClient as cls # type: ignore
  824. return cls( # type: ignore
  825. self, self.response_class, use_cookies=use_cookies, **kwargs
  826. )
  827. def test_cli_runner(self, **kwargs: t.Any) -> "FlaskCliRunner":
  828. """Create a CLI runner for testing CLI commands.
  829. See :ref:`testing-cli`.
  830. Returns an instance of :attr:`test_cli_runner_class`, by default
  831. :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
  832. passed as the first argument.
  833. .. versionadded:: 1.0
  834. """
  835. cls = self.test_cli_runner_class
  836. if cls is None:
  837. from .testing import FlaskCliRunner as cls # type: ignore
  838. return cls(self, **kwargs) # type: ignore
  839. @setupmethod
  840. def register_blueprint(self, blueprint: "Blueprint", **options: t.Any) -> None:
  841. """Register a :class:`~flask.Blueprint` on the application. Keyword
  842. arguments passed to this method will override the defaults set on the
  843. blueprint.
  844. Calls the blueprint's :meth:`~flask.Blueprint.register` method after
  845. recording the blueprint in the application's :attr:`blueprints`.
  846. :param blueprint: The blueprint to register.
  847. :param url_prefix: Blueprint routes will be prefixed with this.
  848. :param subdomain: Blueprint routes will match on this subdomain.
  849. :param url_defaults: Blueprint routes will use these default values for
  850. view arguments.
  851. :param options: Additional keyword arguments are passed to
  852. :class:`~flask.blueprints.BlueprintSetupState`. They can be
  853. accessed in :meth:`~flask.Blueprint.record` callbacks.
  854. .. versionchanged:: 2.0.1
  855. The ``name`` option can be used to change the (pre-dotted)
  856. name the blueprint is registered with. This allows the same
  857. blueprint to be registered multiple times with unique names
  858. for ``url_for``.
  859. .. versionadded:: 0.7
  860. """
  861. blueprint.register(self, options)
  862. def iter_blueprints(self) -> t.ValuesView["Blueprint"]:
  863. """Iterates over all blueprints by the order they were registered.
  864. .. versionadded:: 0.11
  865. """
  866. return self.blueprints.values()
  867. @setupmethod
  868. def add_url_rule(
  869. self,
  870. rule: str,
  871. endpoint: t.Optional[str] = None,
  872. view_func: t.Optional[ft.ViewCallable] = None,
  873. provide_automatic_options: t.Optional[bool] = None,
  874. **options: t.Any,
  875. ) -> None:
  876. if endpoint is None:
  877. endpoint = _endpoint_from_view_func(view_func) # type: ignore
  878. options["endpoint"] = endpoint
  879. methods = options.pop("methods", None)
  880. # if the methods are not given and the view_func object knows its
  881. # methods we can use that instead. If neither exists, we go with
  882. # a tuple of only ``GET`` as default.
  883. if methods is None:
  884. methods = getattr(view_func, "methods", None) or ("GET",)
  885. if isinstance(methods, str):
  886. raise TypeError(
  887. "Allowed methods must be a list of strings, for"
  888. ' example: @app.route(..., methods=["POST"])'
  889. )
  890. methods = {item.upper() for item in methods}
  891. # Methods that should always be added
  892. required_methods = set(getattr(view_func, "required_methods", ()))
  893. # starting with Flask 0.8 the view_func object can disable and
  894. # force-enable the automatic options handling.
  895. if provide_automatic_options is None:
  896. provide_automatic_options = getattr(
  897. view_func, "provide_automatic_options", None
  898. )
  899. if provide_automatic_options is None:
  900. if "OPTIONS" not in methods:
  901. provide_automatic_options = True
  902. required_methods.add("OPTIONS")
  903. else:
  904. provide_automatic_options = False
  905. # Add the required methods now.
  906. methods |= required_methods
  907. rule = self.url_rule_class(rule, methods=methods, **options)
  908. rule.provide_automatic_options = provide_automatic_options # type: ignore
  909. self.url_map.add(rule)
  910. if view_func is not None:
  911. old_func = self.view_functions.get(endpoint)
  912. if old_func is not None and old_func != view_func:
  913. raise AssertionError(
  914. "View function mapping is overwriting an existing"
  915. f" endpoint function: {endpoint}"
  916. )
  917. self.view_functions[endpoint] = view_func
  918. @setupmethod
  919. def template_filter(
  920. self, name: t.Optional[str] = None
  921. ) -> t.Callable[[ft.TemplateFilterCallable], ft.TemplateFilterCallable]:
  922. """A decorator that is used to register custom template filter.
  923. You can specify a name for the filter, otherwise the function
  924. name will be used. Example::
  925. @app.template_filter()
  926. def reverse(s):
  927. return s[::-1]
  928. :param name: the optional name of the filter, otherwise the
  929. function name will be used.
  930. """
  931. def decorator(f: ft.TemplateFilterCallable) -> ft.TemplateFilterCallable:
  932. self.add_template_filter(f, name=name)
  933. return f
  934. return decorator
  935. @setupmethod
  936. def add_template_filter(
  937. self, f: ft.TemplateFilterCallable, name: t.Optional[str] = None
  938. ) -> None:
  939. """Register a custom template filter. Works exactly like the
  940. :meth:`template_filter` decorator.
  941. :param name: the optional name of the filter, otherwise the
  942. function name will be used.
  943. """
  944. self.jinja_env.filters[name or f.__name__] = f
  945. @setupmethod
  946. def template_test(
  947. self, name: t.Optional[str] = None
  948. ) -> t.Callable[[ft.TemplateTestCallable], ft.TemplateTestCallable]:
  949. """A decorator that is used to register custom template test.
  950. You can specify a name for the test, otherwise the function
  951. name will be used. Example::
  952. @app.template_test()
  953. def is_prime(n):
  954. if n == 2:
  955. return True
  956. for i in range(2, int(math.ceil(math.sqrt(n))) + 1):
  957. if n % i == 0:
  958. return False
  959. return True
  960. .. versionadded:: 0.10
  961. :param name: the optional name of the test, otherwise the
  962. function name will be used.
  963. """
  964. def decorator(f: ft.TemplateTestCallable) -> ft.TemplateTestCallable:
  965. self.add_template_test(f, name=name)
  966. return f
  967. return decorator
  968. @setupmethod
  969. def add_template_test(
  970. self, f: ft.TemplateTestCallable, name: t.Optional[str] = None
  971. ) -> None:
  972. """Register a custom template test. Works exactly like the
  973. :meth:`template_test` decorator.
  974. .. versionadded:: 0.10
  975. :param name: the optional name of the test, otherwise the
  976. function name will be used.
  977. """
  978. self.jinja_env.tests[name or f.__name__] = f
  979. @setupmethod
  980. def template_global(
  981. self, name: t.Optional[str] = None
  982. ) -> t.Callable[[ft.TemplateGlobalCallable], ft.TemplateGlobalCallable]:
  983. """A decorator that is used to register a custom template global function.
  984. You can specify a name for the global function, otherwise the function
  985. name will be used. Example::
  986. @app.template_global()
  987. def double(n):
  988. return 2 * n
  989. .. versionadded:: 0.10
  990. :param name: the optional name of the global function, otherwise the
  991. function name will be used.
  992. """
  993. def decorator(f: ft.TemplateGlobalCallable) -> ft.TemplateGlobalCallable:
  994. self.add_template_global(f, name=name)
  995. return f
  996. return decorator
  997. @setupmethod
  998. def add_template_global(
  999. self, f: ft.TemplateGlobalCallable, name: t.Optional[str] = None
  1000. ) -> None:
  1001. """Register a custom template global function. Works exactly like the
  1002. :meth:`template_global` decorator.
  1003. .. versionadded:: 0.10
  1004. :param name: the optional name of the global function, otherwise the
  1005. function name will be used.
  1006. """
  1007. self.jinja_env.globals[name or f.__name__] = f
  1008. @setupmethod
  1009. def before_first_request(
  1010. self, f: ft.BeforeFirstRequestCallable
  1011. ) -> ft.BeforeFirstRequestCallable:
  1012. """Registers a function to be run before the first request to this
  1013. instance of the application.
  1014. The function will be called without any arguments and its return
  1015. value is ignored.
  1016. .. versionadded:: 0.8
  1017. """
  1018. self.before_first_request_funcs.append(f)
  1019. return f
  1020. @setupmethod
  1021. def teardown_appcontext(self, f: ft.TeardownCallable) -> ft.TeardownCallable:
  1022. """Registers a function to be called when the application context
  1023. ends. These functions are typically also called when the request
  1024. context is popped.
  1025. Example::
  1026. ctx = app.app_context()
  1027. ctx.push()
  1028. ...
  1029. ctx.pop()
  1030. When ``ctx.pop()`` is executed in the above example, the teardown
  1031. functions are called just before the app context moves from the
  1032. stack of active contexts. This becomes relevant if you are using
  1033. such constructs in tests.
  1034. Since a request context typically also manages an application
  1035. context it would also be called when you pop a request context.
  1036. When a teardown function was called because of an unhandled exception
  1037. it will be passed an error object. If an :meth:`errorhandler` is
  1038. registered, it will handle the exception and the teardown will not
  1039. receive it.
  1040. The return values of teardown functions are ignored.
  1041. .. versionadded:: 0.9
  1042. """
  1043. self.teardown_appcontext_funcs.append(f)
  1044. return f
  1045. @setupmethod
  1046. def shell_context_processor(self, f: t.Callable) -> t.Callable:
  1047. """Registers a shell context processor function.
  1048. .. versionadded:: 0.11
  1049. """
  1050. self.shell_context_processors.append(f)
  1051. return f
  1052. def _find_error_handler(self, e: Exception) -> t.Optional[ft.ErrorHandlerCallable]:
  1053. """Return a registered error handler for an exception in this order:
  1054. blueprint handler for a specific code, app handler for a specific code,
  1055. blueprint handler for an exception class, app handler for an exception
  1056. class, or ``None`` if a suitable handler is not found.
  1057. """
  1058. exc_class, code = self._get_exc_class_and_code(type(e))
  1059. names = (*request.blueprints, None)
  1060. for c in (code, None) if code is not None else (None,):
  1061. for name in names:
  1062. handler_map = self.error_handler_spec[name][c]
  1063. if not handler_map:
  1064. continue
  1065. for cls in exc_class.__mro__:
  1066. handler = handler_map.get(cls)
  1067. if handler is not None:
  1068. return handler
  1069. return None
  1070. def handle_http_exception(
  1071. self, e: HTTPException
  1072. ) -> t.Union[HTTPException, ft.ResponseReturnValue]:
  1073. """Handles an HTTP exception. By default this will invoke the
  1074. registered error handlers and fall back to returning the
  1075. exception as response.
  1076. .. versionchanged:: 1.0.3
  1077. ``RoutingException``, used internally for actions such as
  1078. slash redirects during routing, is not passed to error
  1079. handlers.
  1080. .. versionchanged:: 1.0
  1081. Exceptions are looked up by code *and* by MRO, so
  1082. ``HTTPException`` subclasses can be handled with a catch-all
  1083. handler for the base ``HTTPException``.
  1084. .. versionadded:: 0.3
  1085. """
  1086. # Proxy exceptions don't have error codes. We want to always return
  1087. # those unchanged as errors
  1088. if e.code is None:
  1089. return e
  1090. # RoutingExceptions are used internally to trigger routing
  1091. # actions, such as slash redirects raising RequestRedirect. They
  1092. # are not raised or handled in user code.
  1093. if isinstance(e, RoutingException):
  1094. return e
  1095. handler = self._find_error_handler(e)
  1096. if handler is None:
  1097. return e
  1098. return self.ensure_sync(handler)(e)
  1099. def trap_http_exception(self, e: Exception) -> bool:
  1100. """Checks if an HTTP exception should be trapped or not. By default
  1101. this will return ``False`` for all exceptions except for a bad request
  1102. key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
  1103. also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
  1104. This is called for all HTTP exceptions raised by a view function.
  1105. If it returns ``True`` for any exception the error handler for this
  1106. exception is not called and it shows up as regular exception in the
  1107. traceback. This is helpful for debugging implicitly raised HTTP
  1108. exceptions.
  1109. .. versionchanged:: 1.0
  1110. Bad request errors are not trapped by default in debug mode.
  1111. .. versionadded:: 0.8
  1112. """
  1113. if self.config["TRAP_HTTP_EXCEPTIONS"]:
  1114. return True
  1115. trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]
  1116. # if unset, trap key errors in debug mode
  1117. if (
  1118. trap_bad_request is None
  1119. and self.debug
  1120. and isinstance(e, BadRequestKeyError)
  1121. ):
  1122. return True
  1123. if trap_bad_request:
  1124. return isinstance(e, BadRequest)
  1125. return False
  1126. def handle_user_exception(
  1127. self, e: Exception
  1128. ) -> t.Union[HTTPException, ft.ResponseReturnValue]:
  1129. """This method is called whenever an exception occurs that
  1130. should be handled. A special case is :class:`~werkzeug
  1131. .exceptions.HTTPException` which is forwarded to the
  1132. :meth:`handle_http_exception` method. This function will either
  1133. return a response value or reraise the exception with the same
  1134. traceback.
  1135. .. versionchanged:: 1.0
  1136. Key errors raised from request data like ``form`` show the
  1137. bad key in debug mode rather than a generic bad request
  1138. message.
  1139. .. versionadded:: 0.7
  1140. """
  1141. if isinstance(e, BadRequestKeyError) and (
  1142. self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]
  1143. ):
  1144. e.show_exception = True
  1145. if isinstance(e, HTTPException) and not self.trap_http_exception(e):
  1146. return self.handle_http_exception(e)
  1147. handler = self._find_error_handler(e)
  1148. if handler is None:
  1149. raise
  1150. return self.ensure_sync(handler)(e)
  1151. def handle_exception(self, e: Exception) -> Response:
  1152. """Handle an exception that did not have an error handler
  1153. associated with it, or that was raised from an error handler.
  1154. This always causes a 500 ``InternalServerError``.
  1155. Always sends the :data:`got_request_exception` signal.
  1156. If :attr:`propagate_exceptions` is ``True``, such as in debug
  1157. mode, the error will be re-raised so that the debugger can
  1158. display it. Otherwise, the original exception is logged, and
  1159. an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
  1160. If an error handler is registered for ``InternalServerError`` or
  1161. ``500``, it will be used. For consistency, the handler will
  1162. always receive the ``InternalServerError``. The original
  1163. unhandled exception is available as ``e.original_exception``.
  1164. .. versionchanged:: 1.1.0
  1165. Always passes the ``InternalServerError`` instance to the
  1166. handler, setting ``original_exception`` to the unhandled
  1167. error.
  1168. .. versionchanged:: 1.1.0
  1169. ``after_request`` functions and other finalization is done
  1170. even for the default 500 response when there is no handler.
  1171. .. versionadded:: 0.3
  1172. """
  1173. exc_info = sys.exc_info()
  1174. got_request_exception.send(self, exception=e)
  1175. if self.propagate_exceptions:
  1176. # Re-raise if called with an active exception, otherwise
  1177. # raise the passed in exception.
  1178. if exc_info[1] is e:
  1179. raise
  1180. raise e
  1181. self.log_exception(exc_info)
  1182. server_error: t.Union[InternalServerError, ft.ResponseReturnValue]
  1183. server_error = InternalServerError(original_exception=e)
  1184. handler = self._find_error_handler(server_error)
  1185. if handler is not None:
  1186. server_error = self.ensure_sync(handler)(server_error)
  1187. return self.finalize_request(server_error, from_error_handler=True)
  1188. def log_exception(
  1189. self,
  1190. exc_info: t.Union[
  1191. t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]
  1192. ],
  1193. ) -> None:
  1194. """Logs an exception. This is called by :meth:`handle_exception`
  1195. if debugging is disabled and right before the handler is called.
  1196. The default implementation logs the exception as error on the
  1197. :attr:`logger`.
  1198. .. versionadded:: 0.8
  1199. """
  1200. self.logger.error(
  1201. f"Exception on {request.path} [{request.method}]", exc_info=exc_info
  1202. )
  1203. def raise_routing_exception(self, request: Request) -> "te.NoReturn":
  1204. """Intercept routing exceptions and possibly do something else.
  1205. In debug mode, intercept a routing redirect and replace it with
  1206. an error if the body will be discarded.
  1207. With modern Werkzeug this shouldn't occur, since it now uses a
  1208. 308 status which tells the browser to resend the method and
  1209. body.
  1210. .. versionchanged:: 2.1
  1211. Don't intercept 307 and 308 redirects.
  1212. :meta private:
  1213. :internal:
  1214. """
  1215. if (
  1216. not self.debug
  1217. or not isinstance(request.routing_exception, RequestRedirect)
  1218. or request.routing_exception.code in {307, 308}
  1219. or request.method in {"GET", "HEAD", "OPTIONS"}
  1220. ):
  1221. raise request.routing_exception # type: ignore
  1222. from .debughelpers import FormDataRoutingRedirect
  1223. raise FormDataRoutingRedirect(request)
  1224. def dispatch_request(self) -> ft.ResponseReturnValue:
  1225. """Does the request dispatching. Matches the URL and returns the
  1226. return value of the view or error handler. This does not have to
  1227. be a response object. In order to convert the return value to a
  1228. proper response object, call :func:`make_response`.
  1229. .. versionchanged:: 0.7
  1230. This no longer does the exception handling, this code was
  1231. moved to the new :meth:`full_dispatch_request`.
  1232. """
  1233. req = _request_ctx_stack.top.request
  1234. if req.routing_exception is not None:
  1235. self.raise_routing_exception(req)
  1236. rule = req.url_rule
  1237. # if we provide automatic options for this URL and the
  1238. # request came with the OPTIONS method, reply automatically
  1239. if (
  1240. getattr(rule, "provide_automatic_options", False)
  1241. and req.method == "OPTIONS"
  1242. ):
  1243. return self.make_default_options_response()
  1244. # otherwise dispatch to the handler for that endpoint
  1245. return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  1246. def full_dispatch_request(self) -> Response:
  1247. """Dispatches the request and on top of that performs request
  1248. pre and postprocessing as well as HTTP exception catching and
  1249. error handling.
  1250. .. versionadded:: 0.7
  1251. """
  1252. self.try_trigger_before_first_request_functions()
  1253. try:
  1254. request_started.send(self)
  1255. rv = self.preprocess_request()
  1256. if rv is None:
  1257. rv = self.dispatch_request()
  1258. except Exception as e:
  1259. rv = self.handle_user_exception(e)
  1260. return self.finalize_request(rv)
  1261. def finalize_request(
  1262. self,
  1263. rv: t.Union[ft.ResponseReturnValue, HTTPException],
  1264. from_error_handler: bool = False,
  1265. ) -> Response:
  1266. """Given the return value from a view function this finalizes
  1267. the request by converting it into a response and invoking the
  1268. postprocessing functions. This is invoked for both normal
  1269. request dispatching as well as error handlers.
  1270. Because this means that it might be called as a result of a
  1271. failure a special safe mode is available which can be enabled
  1272. with the `from_error_handler` flag. If enabled, failures in
  1273. response processing will be logged and otherwise ignored.
  1274. :internal:
  1275. """
  1276. response = self.make_response(rv)
  1277. try:
  1278. response = self.process_response(response)
  1279. request_finished.send(self, response=response)
  1280. except Exception:
  1281. if not from_error_handler:
  1282. raise
  1283. self.logger.exception(
  1284. "Request finalizing failed with an error while handling an error"
  1285. )
  1286. return response
  1287. def try_trigger_before_first_request_functions(self) -> None:
  1288. """Called before each request and will ensure that it triggers
  1289. the :attr:`before_first_request_funcs` and only exactly once per
  1290. application instance (which means process usually).
  1291. :internal:
  1292. """
  1293. if self._got_first_request:
  1294. return
  1295. with self._before_request_lock:
  1296. if self._got_first_request:
  1297. return
  1298. for func in self.before_first_request_funcs:
  1299. self.ensure_sync(func)()
  1300. self._got_first_request = True
  1301. def make_default_options_response(self) -> Response:
  1302. """This method is called to create the default ``OPTIONS`` response.
  1303. This can be changed through subclassing to change the default
  1304. behavior of ``OPTIONS`` responses.
  1305. .. versionadded:: 0.7
  1306. """
  1307. adapter = _request_ctx_stack.top.url_adapter
  1308. methods = adapter.allowed_methods()
  1309. rv = self.response_class()
  1310. rv.allow.update(methods)
  1311. return rv
  1312. def should_ignore_error(self, error: t.Optional[BaseException]) -> bool:
  1313. """This is called to figure out if an error should be ignored
  1314. or not as far as the teardown system is concerned. If this
  1315. function returns ``True`` then the teardown handlers will not be
  1316. passed the error.
  1317. .. versionadded:: 0.10
  1318. """
  1319. return False
  1320. def ensure_sync(self, func: t.Callable) -> t.Callable:
  1321. """Ensure that the function is synchronous for WSGI workers.
  1322. Plain ``def`` functions are returned as-is. ``async def``
  1323. functions are wrapped to run and wait for the response.
  1324. Override this method to change how the app runs async views.
  1325. .. versionadded:: 2.0
  1326. """
  1327. if iscoroutinefunction(func):
  1328. return self.async_to_sync(func)
  1329. return func
  1330. def async_to_sync(
  1331. self, func: t.Callable[..., t.Coroutine]
  1332. ) -> t.Callable[..., t.Any]:
  1333. """Return a sync function that will run the coroutine function.
  1334. .. code-block:: python
  1335. result = app.async_to_sync(func)(*args, **kwargs)
  1336. Override this method to change how the app converts async code
  1337. to be synchronously callable.
  1338. .. versionadded:: 2.0
  1339. """
  1340. try:
  1341. from asgiref.sync import async_to_sync as asgiref_async_to_sync
  1342. except ImportError:
  1343. raise RuntimeError(
  1344. "Install Flask with the 'async' extra in order to use async views."
  1345. ) from None
  1346. return asgiref_async_to_sync(func)
  1347. def make_response(self, rv: ft.ResponseReturnValue) -> Response:
  1348. """Convert the return value from a view function to an instance of
  1349. :attr:`response_class`.
  1350. :param rv: the return value from the view function. The view function
  1351. must return a response. Returning ``None``, or the view ending
  1352. without returning, is not allowed. The following types are allowed
  1353. for ``view_rv``:
  1354. ``str``
  1355. A response object is created with the string encoded to UTF-8
  1356. as the body.
  1357. ``bytes``
  1358. A response object is created with the bytes as the body.
  1359. ``dict``
  1360. A dictionary that will be jsonify'd before being returned.
  1361. ``tuple``
  1362. Either ``(body, status, headers)``, ``(body, status)``, or
  1363. ``(body, headers)``, where ``body`` is any of the other types
  1364. allowed here, ``status`` is a string or an integer, and
  1365. ``headers`` is a dictionary or a list of ``(key, value)``
  1366. tuples. If ``body`` is a :attr:`response_class` instance,
  1367. ``status`` overwrites the exiting value and ``headers`` are
  1368. extended.
  1369. :attr:`response_class`
  1370. The object is returned unchanged.
  1371. other :class:`~werkzeug.wrappers.Response` class
  1372. The object is coerced to :attr:`response_class`.
  1373. :func:`callable`
  1374. The function is called as a WSGI application. The result is
  1375. used to create a response object.
  1376. .. versionchanged:: 0.9
  1377. Previously a tuple was interpreted as the arguments for the
  1378. response object.
  1379. """
  1380. status = headers = None
  1381. # unpack tuple returns
  1382. if isinstance(rv, tuple):
  1383. len_rv = len(rv)
  1384. # a 3-tuple is unpacked directly
  1385. if len_rv == 3:
  1386. rv, status, headers = rv # type: ignore[misc]
  1387. # decide if a 2-tuple has status or headers
  1388. elif len_rv == 2:
  1389. if isinstance(rv[1], (Headers, dict, tuple, list)):
  1390. rv, headers = rv
  1391. else:
  1392. rv, status = rv # type: ignore[assignment,misc]
  1393. # other sized tuples are not allowed
  1394. else:
  1395. raise TypeError(
  1396. "The view function did not return a valid response tuple."
  1397. " The tuple must have the form (body, status, headers),"
  1398. " (body, status), or (body, headers)."
  1399. )
  1400. # the body must not be None
  1401. if rv is None:
  1402. raise TypeError(
  1403. f"The view function for {request.endpoint!r} did not"
  1404. " return a valid response. The function either returned"
  1405. " None or ended without a return statement."
  1406. )
  1407. # make sure the body is an instance of the response class
  1408. if not isinstance(rv, self.response_class):
  1409. if isinstance(rv, (str, bytes, bytearray)):
  1410. # let the response class set the status and headers instead of
  1411. # waiting to do it manually, so that the class can handle any
  1412. # special logic
  1413. rv = self.response_class(
  1414. rv,
  1415. status=status,
  1416. headers=headers, # type: ignore[arg-type]
  1417. )
  1418. status = headers = None
  1419. elif isinstance(rv, dict):
  1420. rv = jsonify(rv)
  1421. elif isinstance(rv, BaseResponse) or callable(rv):
  1422. # evaluate a WSGI callable, or coerce a different response
  1423. # class to the correct type
  1424. try:
  1425. rv = self.response_class.force_type(
  1426. rv, request.environ # type: ignore[arg-type]
  1427. )
  1428. except TypeError as e:
  1429. raise TypeError(
  1430. f"{e}\nThe view function did not return a valid"
  1431. " response. The return type must be a string,"
  1432. " dict, tuple, Response instance, or WSGI"
  1433. f" callable, but it was a {type(rv).__name__}."
  1434. ).with_traceback(sys.exc_info()[2]) from None
  1435. else:
  1436. raise TypeError(
  1437. "The view function did not return a valid"
  1438. " response. The return type must be a string,"
  1439. " dict, tuple, Response instance, or WSGI"
  1440. f" callable, but it was a {type(rv).__name__}."
  1441. )
  1442. rv = t.cast(Response, rv)
  1443. # prefer the status if it was provided
  1444. if status is not None:
  1445. if isinstance(status, (str, bytes, bytearray)):
  1446. rv.status = status
  1447. else:
  1448. rv.status_code = status
  1449. # extend existing headers with provided headers
  1450. if headers:
  1451. rv.headers.update(headers) # type: ignore[arg-type]
  1452. return rv
  1453. def create_url_adapter(
  1454. self, request: t.Optional[Request]
  1455. ) -> t.Optional[MapAdapter]:
  1456. """Creates a URL adapter for the given request. The URL adapter
  1457. is created at a point where the request context is not yet set
  1458. up so the request is passed explicitly.
  1459. .. versionadded:: 0.6
  1460. .. versionchanged:: 0.9
  1461. This can now also be called without a request object when the
  1462. URL adapter is created for the application context.
  1463. .. versionchanged:: 1.0
  1464. :data:`SERVER_NAME` no longer implicitly enables subdomain
  1465. matching. Use :attr:`subdomain_matching` instead.
  1466. """
  1467. if request is not None:
  1468. # If subdomain matching is disabled (the default), use the
  1469. # default subdomain in all cases. This should be the default
  1470. # in Werkzeug but it currently does not have that feature.
  1471. if not self.subdomain_matching:
  1472. subdomain = self.url_map.default_subdomain or None
  1473. else:
  1474. subdomain = None
  1475. return self.url_map.bind_to_environ(
  1476. request.environ,
  1477. server_name=self.config["SERVER_NAME"],
  1478. subdomain=subdomain,
  1479. )
  1480. # We need at the very least the server name to be set for this
  1481. # to work.
  1482. if self.config["SERVER_NAME"] is not None:
  1483. return self.url_map.bind(
  1484. self.config["SERVER_NAME"],
  1485. script_name=self.config["APPLICATION_ROOT"],
  1486. url_scheme=self.config["PREFERRED_URL_SCHEME"],
  1487. )
  1488. return None
  1489. def inject_url_defaults(self, endpoint: str, values: dict) -> None:
  1490. """Injects the URL defaults for the given endpoint directly into
  1491. the values dictionary passed. This is used internally and
  1492. automatically called on URL building.
  1493. .. versionadded:: 0.7
  1494. """
  1495. names: t.Iterable[t.Optional[str]] = (None,)
  1496. # url_for may be called outside a request context, parse the
  1497. # passed endpoint instead of using request.blueprints.
  1498. if "." in endpoint:
  1499. names = chain(
  1500. names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))
  1501. )
  1502. for name in names:
  1503. if name in self.url_default_functions:
  1504. for func in self.url_default_functions[name]:
  1505. func(endpoint, values)
  1506. def handle_url_build_error(
  1507. self, error: Exception, endpoint: str, values: dict
  1508. ) -> str:
  1509. """Handle :class:`~werkzeug.routing.BuildError` on
  1510. :meth:`url_for`.
  1511. """
  1512. for handler in self.url_build_error_handlers:
  1513. try:
  1514. rv = handler(error, endpoint, values)
  1515. except BuildError as e:
  1516. # make error available outside except block
  1517. error = e
  1518. else:
  1519. if rv is not None:
  1520. return rv
  1521. # Re-raise if called with an active exception, otherwise raise
  1522. # the passed in exception.
  1523. if error is sys.exc_info()[1]:
  1524. raise
  1525. raise error
  1526. def preprocess_request(self) -> t.Optional[ft.ResponseReturnValue]:
  1527. """Called before the request is dispatched. Calls
  1528. :attr:`url_value_preprocessors` registered with the app and the
  1529. current blueprint (if any). Then calls :attr:`before_request_funcs`
  1530. registered with the app and the blueprint.
  1531. If any :meth:`before_request` handler returns a non-None value, the
  1532. value is handled as if it was the return value from the view, and
  1533. further request handling is stopped.
  1534. """
  1535. names = (None, *reversed(request.blueprints))
  1536. for name in names:
  1537. if name in self.url_value_preprocessors:
  1538. for url_func in self.url_value_preprocessors[name]:
  1539. url_func(request.endpoint, request.view_args)
  1540. for name in names:
  1541. if name in self.before_request_funcs:
  1542. for before_func in self.before_request_funcs[name]:
  1543. rv = self.ensure_sync(before_func)()
  1544. if rv is not None:
  1545. return rv
  1546. return None
  1547. def process_response(self, response: Response) -> Response:
  1548. """Can be overridden in order to modify the response object
  1549. before it's sent to the WSGI server. By default this will
  1550. call all the :meth:`after_request` decorated functions.
  1551. .. versionchanged:: 0.5
  1552. As of Flask 0.5 the functions registered for after request
  1553. execution are called in reverse order of registration.
  1554. :param response: a :attr:`response_class` object.
  1555. :return: a new response object or the same, has to be an
  1556. instance of :attr:`response_class`.
  1557. """
  1558. ctx = _request_ctx_stack.top
  1559. for func in ctx._after_request_functions:
  1560. response = self.ensure_sync(func)(response)
  1561. for name in chain(request.blueprints, (None,)):
  1562. if name in self.after_request_funcs:
  1563. for func in reversed(self.after_request_funcs[name]):
  1564. response = self.ensure_sync(func)(response)
  1565. if not self.session_interface.is_null_session(ctx.session):
  1566. self.session_interface.save_session(self, ctx.session, response)
  1567. return response
  1568. def do_teardown_request(
  1569. self, exc: t.Optional[BaseException] = _sentinel # type: ignore
  1570. ) -> None:
  1571. """Called after the request is dispatched and the response is
  1572. returned, right before the request context is popped.
  1573. This calls all functions decorated with
  1574. :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
  1575. if a blueprint handled the request. Finally, the
  1576. :data:`request_tearing_down` signal is sent.
  1577. This is called by
  1578. :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,
  1579. which may be delayed during testing to maintain access to
  1580. resources.
  1581. :param exc: An unhandled exception raised while dispatching the
  1582. request. Detected from the current exception information if
  1583. not passed. Passed to each teardown function.
  1584. .. versionchanged:: 0.9
  1585. Added the ``exc`` argument.
  1586. """
  1587. if exc is _sentinel:
  1588. exc = sys.exc_info()[1]
  1589. for name in chain(request.blueprints, (None,)):
  1590. if name in self.teardown_request_funcs:
  1591. for func in reversed(self.teardown_request_funcs[name]):
  1592. self.ensure_sync(func)(exc)
  1593. request_tearing_down.send(self, exc=exc)
  1594. def do_teardown_appcontext(
  1595. self, exc: t.Optional[BaseException] = _sentinel # type: ignore
  1596. ) -> None:
  1597. """Called right before the application context is popped.
  1598. When handling a request, the application context is popped
  1599. after the request context. See :meth:`do_teardown_request`.
  1600. This calls all functions decorated with
  1601. :meth:`teardown_appcontext`. Then the
  1602. :data:`appcontext_tearing_down` signal is sent.
  1603. This is called by
  1604. :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.
  1605. .. versionadded:: 0.9
  1606. """
  1607. if exc is _sentinel:
  1608. exc = sys.exc_info()[1]
  1609. for func in reversed(self.teardown_appcontext_funcs):
  1610. self.ensure_sync(func)(exc)
  1611. appcontext_tearing_down.send(self, exc=exc)
  1612. def app_context(self) -> AppContext:
  1613. """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
  1614. block to push the context, which will make :data:`current_app`
  1615. point at this application.
  1616. An application context is automatically pushed by
  1617. :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
  1618. when handling a request, and when running a CLI command. Use
  1619. this to manually create a context outside of these situations.
  1620. ::
  1621. with app.app_context():
  1622. init_db()
  1623. See :doc:`/appcontext`.
  1624. .. versionadded:: 0.9
  1625. """
  1626. return AppContext(self)
  1627. def request_context(self, environ: dict) -> RequestContext:
  1628. """Create a :class:`~flask.ctx.RequestContext` representing a
  1629. WSGI environment. Use a ``with`` block to push the context,
  1630. which will make :data:`request` point at this request.
  1631. See :doc:`/reqcontext`.
  1632. Typically you should not call this from your own code. A request
  1633. context is automatically pushed by the :meth:`wsgi_app` when
  1634. handling a request. Use :meth:`test_request_context` to create
  1635. an environment and context instead of this method.
  1636. :param environ: a WSGI environment
  1637. """
  1638. return RequestContext(self, environ)
  1639. def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:
  1640. """Create a :class:`~flask.ctx.RequestContext` for a WSGI
  1641. environment created from the given values. This is mostly useful
  1642. during testing, where you may want to run a function that uses
  1643. request data without dispatching a full request.
  1644. See :doc:`/reqcontext`.
  1645. Use a ``with`` block to push the context, which will make
  1646. :data:`request` point at the request for the created
  1647. environment. ::
  1648. with test_request_context(...):
  1649. generate_report()
  1650. When using the shell, it may be easier to push and pop the
  1651. context manually to avoid indentation. ::
  1652. ctx = app.test_request_context(...)
  1653. ctx.push()
  1654. ...
  1655. ctx.pop()
  1656. Takes the same arguments as Werkzeug's
  1657. :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
  1658. the application. See the linked Werkzeug docs for most of the
  1659. available arguments. Flask-specific behavior is listed here.
  1660. :param path: URL path being requested.
  1661. :param base_url: Base URL where the app is being served, which
  1662. ``path`` is relative to. If not given, built from
  1663. :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
  1664. :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
  1665. :param subdomain: Subdomain name to append to
  1666. :data:`SERVER_NAME`.
  1667. :param url_scheme: Scheme to use instead of
  1668. :data:`PREFERRED_URL_SCHEME`.
  1669. :param data: The request body, either as a string or a dict of
  1670. form keys and values.
  1671. :param json: If given, this is serialized as JSON and passed as
  1672. ``data``. Also defaults ``content_type`` to
  1673. ``application/json``.
  1674. :param args: other positional arguments passed to
  1675. :class:`~werkzeug.test.EnvironBuilder`.
  1676. :param kwargs: other keyword arguments passed to
  1677. :class:`~werkzeug.test.EnvironBuilder`.
  1678. """
  1679. from .testing import EnvironBuilder
  1680. builder = EnvironBuilder(self, *args, **kwargs)
  1681. try:
  1682. return self.request_context(builder.get_environ())
  1683. finally:
  1684. builder.close()
  1685. def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:
  1686. """The actual WSGI application. This is not implemented in
  1687. :meth:`__call__` so that middlewares can be applied without
  1688. losing a reference to the app object. Instead of doing this::
  1689. app = MyMiddleware(app)
  1690. It's a better idea to do this instead::
  1691. app.wsgi_app = MyMiddleware(app.wsgi_app)
  1692. Then you still have the original application object around and
  1693. can continue to call methods on it.
  1694. .. versionchanged:: 0.7
  1695. Teardown events for the request and app contexts are called
  1696. even if an unhandled error occurs. Other events may not be
  1697. called depending on when an error occurs during dispatch.
  1698. See :ref:`callbacks-and-errors`.
  1699. :param environ: A WSGI environment.
  1700. :param start_response: A callable accepting a status code,
  1701. a list of headers, and an optional exception context to
  1702. start the response.
  1703. """
  1704. ctx = self.request_context(environ)
  1705. error: t.Optional[BaseException] = None
  1706. try:
  1707. try:
  1708. ctx.push()
  1709. response = self.full_dispatch_request()
  1710. except Exception as e:
  1711. error = e
  1712. response = self.handle_exception(e)
  1713. except: # noqa: B001
  1714. error = sys.exc_info()[1]
  1715. raise
  1716. return response(environ, start_response)
  1717. finally:
  1718. if self.should_ignore_error(error):
  1719. error = None
  1720. ctx.auto_pop(error)
  1721. def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:
  1722. """The WSGI server calls the Flask application object as the
  1723. WSGI application. This calls :meth:`wsgi_app`, which can be
  1724. wrapped to apply middleware.
  1725. """
  1726. return self.wsgi_app(environ, start_response)