app.py 80 KB

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