app.py 97 KB

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