app.py 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091
  1. import functools
  2. import inspect
  3. import logging
  4. import os
  5. import sys
  6. import typing as t
  7. import weakref
  8. from datetime import timedelta
  9. from itertools import chain
  10. from threading import Lock
  11. from types import TracebackType
  12. from werkzeug.datastructures import Headers
  13. from werkzeug.datastructures import ImmutableDict
  14. from werkzeug.exceptions import BadRequest
  15. from werkzeug.exceptions import BadRequestKeyError
  16. from werkzeug.exceptions import HTTPException
  17. from werkzeug.exceptions import InternalServerError
  18. from werkzeug.local import ContextVar
  19. from werkzeug.routing import BuildError
  20. from werkzeug.routing import Map
  21. from werkzeug.routing import MapAdapter
  22. from werkzeug.routing import RequestRedirect
  23. from werkzeug.routing import RoutingException
  24. from werkzeug.routing import Rule
  25. from werkzeug.wrappers import Response as BaseResponse
  26. from . import cli
  27. from . import json
  28. from .config import Config
  29. from .config import ConfigAttribute
  30. from .ctx import _AppCtxGlobals
  31. from .ctx import AppContext
  32. from .ctx import RequestContext
  33. from .globals import _request_ctx_stack
  34. from .globals import g
  35. from .globals import request
  36. from .globals import session
  37. from .helpers import _split_blueprint_path
  38. from .helpers import get_debug_flag
  39. from .helpers import get_env
  40. from .helpers import get_flashed_messages
  41. from .helpers import get_load_dotenv
  42. from .helpers import locked_cached_property
  43. from .helpers import url_for
  44. from .json import jsonify
  45. from .logging import create_logger
  46. from .scaffold import _endpoint_from_view_func
  47. from .scaffold import _sentinel
  48. from .scaffold import find_package
  49. from .scaffold import Scaffold
  50. from .scaffold import setupmethod
  51. from .sessions import SecureCookieSessionInterface
  52. from .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 = 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(
  1059. self, e: Exception
  1060. ) -> t.Optional["ErrorHandlerCallable[Exception]"]:
  1061. """Return a registered error handler for an exception in this order:
  1062. blueprint handler for a specific code, app handler for a specific code,
  1063. blueprint handler for an exception class, app handler for an exception
  1064. class, or ``None`` if a suitable handler is not found.
  1065. """
  1066. exc_class, code = self._get_exc_class_and_code(type(e))
  1067. names = (*request.blueprints, None)
  1068. for c in (code, None) if code is not None else (None,):
  1069. for name in names:
  1070. handler_map = self.error_handler_spec[name][c]
  1071. if not handler_map:
  1072. continue
  1073. for cls in exc_class.__mro__:
  1074. handler = handler_map.get(cls)
  1075. if handler is not None:
  1076. return handler
  1077. return None
  1078. def handle_http_exception(
  1079. self, e: HTTPException
  1080. ) -> t.Union[HTTPException, ResponseReturnValue]:
  1081. """Handles an HTTP exception. By default this will invoke the
  1082. registered error handlers and fall back to returning the
  1083. exception as response.
  1084. .. versionchanged:: 1.0.3
  1085. ``RoutingException``, used internally for actions such as
  1086. slash redirects during routing, is not passed to error
  1087. handlers.
  1088. .. versionchanged:: 1.0
  1089. Exceptions are looked up by code *and* by MRO, so
  1090. ``HTTPException`` subclasses can be handled with a catch-all
  1091. handler for the base ``HTTPException``.
  1092. .. versionadded:: 0.3
  1093. """
  1094. # Proxy exceptions don't have error codes. We want to always return
  1095. # those unchanged as errors
  1096. if e.code is None:
  1097. return e
  1098. # RoutingExceptions are used internally to trigger routing
  1099. # actions, such as slash redirects raising RequestRedirect. They
  1100. # are not raised or handled in user code.
  1101. if isinstance(e, RoutingException):
  1102. return e
  1103. handler = self._find_error_handler(e)
  1104. if handler is None:
  1105. return e
  1106. return self.ensure_sync(handler)(e)
  1107. def trap_http_exception(self, e: Exception) -> bool:
  1108. """Checks if an HTTP exception should be trapped or not. By default
  1109. this will return ``False`` for all exceptions except for a bad request
  1110. key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It
  1111. also returns ``True`` if ``TRAP_HTTP_EXCEPTIONS`` is set to ``True``.
  1112. This is called for all HTTP exceptions raised by a view function.
  1113. If it returns ``True`` for any exception the error handler for this
  1114. exception is not called and it shows up as regular exception in the
  1115. traceback. This is helpful for debugging implicitly raised HTTP
  1116. exceptions.
  1117. .. versionchanged:: 1.0
  1118. Bad request errors are not trapped by default in debug mode.
  1119. .. versionadded:: 0.8
  1120. """
  1121. if self.config["TRAP_HTTP_EXCEPTIONS"]:
  1122. return True
  1123. trap_bad_request = self.config["TRAP_BAD_REQUEST_ERRORS"]
  1124. # if unset, trap key errors in debug mode
  1125. if (
  1126. trap_bad_request is None
  1127. and self.debug
  1128. and isinstance(e, BadRequestKeyError)
  1129. ):
  1130. return True
  1131. if trap_bad_request:
  1132. return isinstance(e, BadRequest)
  1133. return False
  1134. def handle_user_exception(
  1135. self, e: Exception
  1136. ) -> t.Union[HTTPException, ResponseReturnValue]:
  1137. """This method is called whenever an exception occurs that
  1138. should be handled. A special case is :class:`~werkzeug
  1139. .exceptions.HTTPException` which is forwarded to the
  1140. :meth:`handle_http_exception` method. This function will either
  1141. return a response value or reraise the exception with the same
  1142. traceback.
  1143. .. versionchanged:: 1.0
  1144. Key errors raised from request data like ``form`` show the
  1145. bad key in debug mode rather than a generic bad request
  1146. message.
  1147. .. versionadded:: 0.7
  1148. """
  1149. if isinstance(e, BadRequestKeyError) and (
  1150. self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]
  1151. ):
  1152. e.show_exception = True
  1153. if isinstance(e, HTTPException) and not self.trap_http_exception(e):
  1154. return self.handle_http_exception(e)
  1155. handler = self._find_error_handler(e)
  1156. if handler is None:
  1157. raise
  1158. return self.ensure_sync(handler)(e)
  1159. def handle_exception(self, e: Exception) -> Response:
  1160. """Handle an exception that did not have an error handler
  1161. associated with it, or that was raised from an error handler.
  1162. This always causes a 500 ``InternalServerError``.
  1163. Always sends the :data:`got_request_exception` signal.
  1164. If :attr:`propagate_exceptions` is ``True``, such as in debug
  1165. mode, the error will be re-raised so that the debugger can
  1166. display it. Otherwise, the original exception is logged, and
  1167. an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
  1168. If an error handler is registered for ``InternalServerError`` or
  1169. ``500``, it will be used. For consistency, the handler will
  1170. always receive the ``InternalServerError``. The original
  1171. unhandled exception is available as ``e.original_exception``.
  1172. .. versionchanged:: 1.1.0
  1173. Always passes the ``InternalServerError`` instance to the
  1174. handler, setting ``original_exception`` to the unhandled
  1175. error.
  1176. .. versionchanged:: 1.1.0
  1177. ``after_request`` functions and other finalization is done
  1178. even for the default 500 response when there is no handler.
  1179. .. versionadded:: 0.3
  1180. """
  1181. exc_info = sys.exc_info()
  1182. got_request_exception.send(self, exception=e)
  1183. if self.propagate_exceptions:
  1184. # Re-raise if called with an active exception, otherwise
  1185. # raise the passed in exception.
  1186. if exc_info[1] is e:
  1187. raise
  1188. raise e
  1189. self.log_exception(exc_info)
  1190. server_error: t.Union[InternalServerError, ResponseReturnValue]
  1191. server_error = InternalServerError(original_exception=e)
  1192. handler = self._find_error_handler(server_error)
  1193. if handler is not None:
  1194. server_error = self.ensure_sync(handler)(server_error)
  1195. return self.finalize_request(server_error, from_error_handler=True)
  1196. def log_exception(
  1197. self,
  1198. exc_info: t.Union[
  1199. t.Tuple[type, BaseException, TracebackType], t.Tuple[None, None, None]
  1200. ],
  1201. ) -> None:
  1202. """Logs an exception. This is called by :meth:`handle_exception`
  1203. if debugging is disabled and right before the handler is called.
  1204. The default implementation logs the exception as error on the
  1205. :attr:`logger`.
  1206. .. versionadded:: 0.8
  1207. """
  1208. self.logger.error(
  1209. f"Exception on {request.path} [{request.method}]", exc_info=exc_info
  1210. )
  1211. def raise_routing_exception(self, request: Request) -> "te.NoReturn":
  1212. """Exceptions that are recording during routing are reraised with
  1213. this method. During debug we are not reraising redirect requests
  1214. for non ``GET``, ``HEAD``, or ``OPTIONS`` requests and we're raising
  1215. a different error instead to help debug situations.
  1216. :internal:
  1217. """
  1218. if (
  1219. not self.debug
  1220. or not isinstance(request.routing_exception, RequestRedirect)
  1221. or request.method in ("GET", "HEAD", "OPTIONS")
  1222. ):
  1223. raise request.routing_exception # type: ignore
  1224. from .debughelpers import FormDataRoutingRedirect
  1225. raise FormDataRoutingRedirect(request)
  1226. def dispatch_request(self) -> ResponseReturnValue:
  1227. """Does the request dispatching. Matches the URL and returns the
  1228. return value of the view or error handler. This does not have to
  1229. be a response object. In order to convert the return value to a
  1230. proper response object, call :func:`make_response`.
  1231. .. versionchanged:: 0.7
  1232. This no longer does the exception handling, this code was
  1233. moved to the new :meth:`full_dispatch_request`.
  1234. """
  1235. req = _request_ctx_stack.top.request
  1236. if req.routing_exception is not None:
  1237. self.raise_routing_exception(req)
  1238. rule = req.url_rule
  1239. # if we provide automatic options for this URL and the
  1240. # request came with the OPTIONS method, reply automatically
  1241. if (
  1242. getattr(rule, "provide_automatic_options", False)
  1243. and req.method == "OPTIONS"
  1244. ):
  1245. return self.make_default_options_response()
  1246. # otherwise dispatch to the handler for that endpoint
  1247. return self.ensure_sync(self.view_functions[rule.endpoint])(**req.view_args)
  1248. def full_dispatch_request(self) -> Response:
  1249. """Dispatches the request and on top of that performs request
  1250. pre and postprocessing as well as HTTP exception catching and
  1251. error handling.
  1252. .. versionadded:: 0.7
  1253. """
  1254. self.try_trigger_before_first_request_functions()
  1255. try:
  1256. request_started.send(self)
  1257. rv = self.preprocess_request()
  1258. if rv is None:
  1259. rv = self.dispatch_request()
  1260. except Exception as e:
  1261. rv = self.handle_user_exception(e)
  1262. return self.finalize_request(rv)
  1263. def finalize_request(
  1264. self,
  1265. rv: t.Union[ResponseReturnValue, HTTPException],
  1266. from_error_handler: bool = False,
  1267. ) -> Response:
  1268. """Given the return value from a view function this finalizes
  1269. the request by converting it into a response and invoking the
  1270. postprocessing functions. This is invoked for both normal
  1271. request dispatching as well as error handlers.
  1272. Because this means that it might be called as a result of a
  1273. failure a special safe mode is available which can be enabled
  1274. with the `from_error_handler` flag. If enabled, failures in
  1275. response processing will be logged and otherwise ignored.
  1276. :internal:
  1277. """
  1278. response = self.make_response(rv)
  1279. try:
  1280. response = self.process_response(response)
  1281. request_finished.send(self, response=response)
  1282. except Exception:
  1283. if not from_error_handler:
  1284. raise
  1285. self.logger.exception(
  1286. "Request finalizing failed with an error while handling an error"
  1287. )
  1288. return response
  1289. def try_trigger_before_first_request_functions(self) -> None:
  1290. """Called before each request and will ensure that it triggers
  1291. the :attr:`before_first_request_funcs` and only exactly once per
  1292. application instance (which means process usually).
  1293. :internal:
  1294. """
  1295. if self._got_first_request:
  1296. return
  1297. with self._before_request_lock:
  1298. if self._got_first_request:
  1299. return
  1300. for func in self.before_first_request_funcs:
  1301. self.ensure_sync(func)()
  1302. self._got_first_request = True
  1303. def make_default_options_response(self) -> Response:
  1304. """This method is called to create the default ``OPTIONS`` response.
  1305. This can be changed through subclassing to change the default
  1306. behavior of ``OPTIONS`` responses.
  1307. .. versionadded:: 0.7
  1308. """
  1309. adapter = _request_ctx_stack.top.url_adapter
  1310. methods = adapter.allowed_methods()
  1311. rv = self.response_class()
  1312. rv.allow.update(methods)
  1313. return rv
  1314. def should_ignore_error(self, error: t.Optional[BaseException]) -> bool:
  1315. """This is called to figure out if an error should be ignored
  1316. or not as far as the teardown system is concerned. If this
  1317. function returns ``True`` then the teardown handlers will not be
  1318. passed the error.
  1319. .. versionadded:: 0.10
  1320. """
  1321. return False
  1322. def ensure_sync(self, func: t.Callable) -> t.Callable:
  1323. """Ensure that the function is synchronous for WSGI workers.
  1324. Plain ``def`` functions are returned as-is. ``async def``
  1325. functions are wrapped to run and wait for the response.
  1326. Override this method to change how the app runs async views.
  1327. .. versionadded:: 2.0
  1328. """
  1329. if iscoroutinefunction(func):
  1330. return self.async_to_sync(func)
  1331. return func
  1332. def async_to_sync(
  1333. self, func: t.Callable[..., t.Coroutine]
  1334. ) -> t.Callable[..., t.Any]:
  1335. """Return a sync function that will run the coroutine function.
  1336. .. code-block:: python
  1337. result = app.async_to_sync(func)(*args, **kwargs)
  1338. Override this method to change how the app converts async code
  1339. to be synchronously callable.
  1340. .. versionadded:: 2.0
  1341. """
  1342. try:
  1343. from asgiref.sync import async_to_sync as asgiref_async_to_sync
  1344. except ImportError:
  1345. raise RuntimeError(
  1346. "Install Flask with the 'async' extra in order to use async views."
  1347. ) from None
  1348. # Check that Werkzeug isn't using its fallback ContextVar class.
  1349. if ContextVar.__module__ == "werkzeug.local":
  1350. raise RuntimeError(
  1351. "Async cannot be used with this combination of Python "
  1352. "and Greenlet versions."
  1353. )
  1354. return asgiref_async_to_sync(func)
  1355. def make_response(self, rv: ResponseReturnValue) -> Response:
  1356. """Convert the return value from a view function to an instance of
  1357. :attr:`response_class`.
  1358. :param rv: the return value from the view function. The view function
  1359. must return a response. Returning ``None``, or the view ending
  1360. without returning, is not allowed. The following types are allowed
  1361. for ``view_rv``:
  1362. ``str``
  1363. A response object is created with the string encoded to UTF-8
  1364. as the body.
  1365. ``bytes``
  1366. A response object is created with the bytes as the body.
  1367. ``dict``
  1368. A dictionary that will be jsonify'd before being returned.
  1369. ``tuple``
  1370. Either ``(body, status, headers)``, ``(body, status)``, or
  1371. ``(body, headers)``, where ``body`` is any of the other types
  1372. allowed here, ``status`` is a string or an integer, and
  1373. ``headers`` is a dictionary or a list of ``(key, value)``
  1374. tuples. If ``body`` is a :attr:`response_class` instance,
  1375. ``status`` overwrites the exiting value and ``headers`` are
  1376. extended.
  1377. :attr:`response_class`
  1378. The object is returned unchanged.
  1379. other :class:`~werkzeug.wrappers.Response` class
  1380. The object is coerced to :attr:`response_class`.
  1381. :func:`callable`
  1382. The function is called as a WSGI application. The result is
  1383. used to create a response object.
  1384. .. versionchanged:: 0.9
  1385. Previously a tuple was interpreted as the arguments for the
  1386. response object.
  1387. """
  1388. status = headers = None
  1389. # unpack tuple returns
  1390. if isinstance(rv, tuple):
  1391. len_rv = len(rv)
  1392. # a 3-tuple is unpacked directly
  1393. if len_rv == 3:
  1394. rv, status, headers = rv
  1395. # decide if a 2-tuple has status or headers
  1396. elif len_rv == 2:
  1397. if isinstance(rv[1], (Headers, dict, tuple, list)):
  1398. rv, headers = rv
  1399. else:
  1400. rv, status = rv
  1401. # other sized tuples are not allowed
  1402. else:
  1403. raise TypeError(
  1404. "The view function did not return a valid response tuple."
  1405. " The tuple must have the form (body, status, headers),"
  1406. " (body, status), or (body, headers)."
  1407. )
  1408. # the body must not be None
  1409. if rv is None:
  1410. raise TypeError(
  1411. f"The view function for {request.endpoint!r} did not"
  1412. " return a valid response. The function either returned"
  1413. " None or ended without a return statement."
  1414. )
  1415. # make sure the body is an instance of the response class
  1416. if not isinstance(rv, self.response_class):
  1417. if isinstance(rv, (str, bytes, bytearray)):
  1418. # let the response class set the status and headers instead of
  1419. # waiting to do it manually, so that the class can handle any
  1420. # special logic
  1421. rv = self.response_class(rv, status=status, headers=headers)
  1422. status = headers = None
  1423. elif isinstance(rv, dict):
  1424. rv = jsonify(rv)
  1425. elif isinstance(rv, BaseResponse) or callable(rv):
  1426. # evaluate a WSGI callable, or coerce a different response
  1427. # class to the correct type
  1428. try:
  1429. rv = self.response_class.force_type(rv, request.environ) # type: ignore # noqa: B950
  1430. except TypeError as e:
  1431. raise TypeError(
  1432. f"{e}\nThe view function did not return a valid"
  1433. " response. The return type must be a string,"
  1434. " dict, tuple, Response instance, or WSGI"
  1435. f" callable, but it was a {type(rv).__name__}."
  1436. ).with_traceback(sys.exc_info()[2]) from None
  1437. else:
  1438. raise TypeError(
  1439. "The view function did not return a valid"
  1440. " response. The return type must be a string,"
  1441. " dict, tuple, Response instance, or WSGI"
  1442. f" callable, but it was a {type(rv).__name__}."
  1443. )
  1444. rv = t.cast(Response, rv)
  1445. # prefer the status if it was provided
  1446. if status is not None:
  1447. if isinstance(status, (str, bytes, bytearray)):
  1448. rv.status = status # type: ignore
  1449. else:
  1450. rv.status_code = status
  1451. # extend existing headers with provided headers
  1452. if headers:
  1453. rv.headers.update(headers)
  1454. return rv
  1455. def create_url_adapter(
  1456. self, request: t.Optional[Request]
  1457. ) -> t.Optional[MapAdapter]:
  1458. """Creates a URL adapter for the given request. The URL adapter
  1459. is created at a point where the request context is not yet set
  1460. up so the request is passed explicitly.
  1461. .. versionadded:: 0.6
  1462. .. versionchanged:: 0.9
  1463. This can now also be called without a request object when the
  1464. URL adapter is created for the application context.
  1465. .. versionchanged:: 1.0
  1466. :data:`SERVER_NAME` no longer implicitly enables subdomain
  1467. matching. Use :attr:`subdomain_matching` instead.
  1468. """
  1469. if request is not None:
  1470. # If subdomain matching is disabled (the default), use the
  1471. # default subdomain in all cases. This should be the default
  1472. # in Werkzeug but it currently does not have that feature.
  1473. if not self.subdomain_matching:
  1474. subdomain = self.url_map.default_subdomain or None
  1475. else:
  1476. subdomain = None
  1477. return self.url_map.bind_to_environ(
  1478. request.environ,
  1479. server_name=self.config["SERVER_NAME"],
  1480. subdomain=subdomain,
  1481. )
  1482. # We need at the very least the server name to be set for this
  1483. # to work.
  1484. if self.config["SERVER_NAME"] is not None:
  1485. return self.url_map.bind(
  1486. self.config["SERVER_NAME"],
  1487. script_name=self.config["APPLICATION_ROOT"],
  1488. url_scheme=self.config["PREFERRED_URL_SCHEME"],
  1489. )
  1490. return None
  1491. def inject_url_defaults(self, endpoint: str, values: dict) -> None:
  1492. """Injects the URL defaults for the given endpoint directly into
  1493. the values dictionary passed. This is used internally and
  1494. automatically called on URL building.
  1495. .. versionadded:: 0.7
  1496. """
  1497. names: t.Iterable[t.Optional[str]] = (None,)
  1498. # url_for may be called outside a request context, parse the
  1499. # passed endpoint instead of using request.blueprints.
  1500. if "." in endpoint:
  1501. names = chain(
  1502. names, reversed(_split_blueprint_path(endpoint.rpartition(".")[0]))
  1503. )
  1504. for name in names:
  1505. if name in self.url_default_functions:
  1506. for func in self.url_default_functions[name]:
  1507. func(endpoint, values)
  1508. def handle_url_build_error(
  1509. self, error: Exception, endpoint: str, values: dict
  1510. ) -> str:
  1511. """Handle :class:`~werkzeug.routing.BuildError` on
  1512. :meth:`url_for`.
  1513. """
  1514. for handler in self.url_build_error_handlers:
  1515. try:
  1516. rv = handler(error, endpoint, values)
  1517. except BuildError as e:
  1518. # make error available outside except block
  1519. error = e
  1520. else:
  1521. if rv is not None:
  1522. return rv
  1523. # Re-raise if called with an active exception, otherwise raise
  1524. # the passed in exception.
  1525. if error is sys.exc_info()[1]:
  1526. raise
  1527. raise error
  1528. def preprocess_request(self) -> t.Optional[ResponseReturnValue]:
  1529. """Called before the request is dispatched. Calls
  1530. :attr:`url_value_preprocessors` registered with the app and the
  1531. current blueprint (if any). Then calls :attr:`before_request_funcs`
  1532. registered with the app and the blueprint.
  1533. If any :meth:`before_request` handler returns a non-None value, the
  1534. value is handled as if it was the return value from the view, and
  1535. further request handling is stopped.
  1536. """
  1537. names = (None, *reversed(request.blueprints))
  1538. for name in names:
  1539. if name in self.url_value_preprocessors:
  1540. for url_func in self.url_value_preprocessors[name]:
  1541. url_func(request.endpoint, request.view_args)
  1542. for name in names:
  1543. if name in self.before_request_funcs:
  1544. for before_func in self.before_request_funcs[name]:
  1545. rv = self.ensure_sync(before_func)()
  1546. if rv is not None:
  1547. return rv
  1548. return None
  1549. def process_response(self, response: Response) -> Response:
  1550. """Can be overridden in order to modify the response object
  1551. before it's sent to the WSGI server. By default this will
  1552. call all the :meth:`after_request` decorated functions.
  1553. .. versionchanged:: 0.5
  1554. As of Flask 0.5 the functions registered for after request
  1555. execution are called in reverse order of registration.
  1556. :param response: a :attr:`response_class` object.
  1557. :return: a new response object or the same, has to be an
  1558. instance of :attr:`response_class`.
  1559. """
  1560. ctx = _request_ctx_stack.top
  1561. for func in ctx._after_request_functions:
  1562. response = self.ensure_sync(func)(response)
  1563. for name in chain(request.blueprints, (None,)):
  1564. if name in self.after_request_funcs:
  1565. for func in reversed(self.after_request_funcs[name]):
  1566. response = self.ensure_sync(func)(response)
  1567. if not self.session_interface.is_null_session(ctx.session):
  1568. self.session_interface.save_session(self, ctx.session, response)
  1569. return response
  1570. def do_teardown_request(
  1571. self, exc: t.Optional[BaseException] = _sentinel # type: ignore
  1572. ) -> None:
  1573. """Called after the request is dispatched and the response is
  1574. returned, right before the request context is popped.
  1575. This calls all functions decorated with
  1576. :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
  1577. if a blueprint handled the request. Finally, the
  1578. :data:`request_tearing_down` signal is sent.
  1579. This is called by
  1580. :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,
  1581. which may be delayed during testing to maintain access to
  1582. resources.
  1583. :param exc: An unhandled exception raised while dispatching the
  1584. request. Detected from the current exception information if
  1585. not passed. Passed to each teardown function.
  1586. .. versionchanged:: 0.9
  1587. Added the ``exc`` argument.
  1588. """
  1589. if exc is _sentinel:
  1590. exc = sys.exc_info()[1]
  1591. for name in chain(request.blueprints, (None,)):
  1592. if name in self.teardown_request_funcs:
  1593. for func in reversed(self.teardown_request_funcs[name]):
  1594. self.ensure_sync(func)(exc)
  1595. request_tearing_down.send(self, exc=exc)
  1596. def do_teardown_appcontext(
  1597. self, exc: t.Optional[BaseException] = _sentinel # type: ignore
  1598. ) -> None:
  1599. """Called right before the application context is popped.
  1600. When handling a request, the application context is popped
  1601. after the request context. See :meth:`do_teardown_request`.
  1602. This calls all functions decorated with
  1603. :meth:`teardown_appcontext`. Then the
  1604. :data:`appcontext_tearing_down` signal is sent.
  1605. This is called by
  1606. :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.
  1607. .. versionadded:: 0.9
  1608. """
  1609. if exc is _sentinel:
  1610. exc = sys.exc_info()[1]
  1611. for func in reversed(self.teardown_appcontext_funcs):
  1612. self.ensure_sync(func)(exc)
  1613. appcontext_tearing_down.send(self, exc=exc)
  1614. def app_context(self) -> AppContext:
  1615. """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
  1616. block to push the context, which will make :data:`current_app`
  1617. point at this application.
  1618. An application context is automatically pushed by
  1619. :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
  1620. when handling a request, and when running a CLI command. Use
  1621. this to manually create a context outside of these situations.
  1622. ::
  1623. with app.app_context():
  1624. init_db()
  1625. See :doc:`/appcontext`.
  1626. .. versionadded:: 0.9
  1627. """
  1628. return AppContext(self)
  1629. def request_context(self, environ: dict) -> RequestContext:
  1630. """Create a :class:`~flask.ctx.RequestContext` representing a
  1631. WSGI environment. Use a ``with`` block to push the context,
  1632. which will make :data:`request` point at this request.
  1633. See :doc:`/reqcontext`.
  1634. Typically you should not call this from your own code. A request
  1635. context is automatically pushed by the :meth:`wsgi_app` when
  1636. handling a request. Use :meth:`test_request_context` to create
  1637. an environment and context instead of this method.
  1638. :param environ: a WSGI environment
  1639. """
  1640. return RequestContext(self, environ)
  1641. def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:
  1642. """Create a :class:`~flask.ctx.RequestContext` for a WSGI
  1643. environment created from the given values. This is mostly useful
  1644. during testing, where you may want to run a function that uses
  1645. request data without dispatching a full request.
  1646. See :doc:`/reqcontext`.
  1647. Use a ``with`` block to push the context, which will make
  1648. :data:`request` point at the request for the created
  1649. environment. ::
  1650. with test_request_context(...):
  1651. generate_report()
  1652. When using the shell, it may be easier to push and pop the
  1653. context manually to avoid indentation. ::
  1654. ctx = app.test_request_context(...)
  1655. ctx.push()
  1656. ...
  1657. ctx.pop()
  1658. Takes the same arguments as Werkzeug's
  1659. :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
  1660. the application. See the linked Werkzeug docs for most of the
  1661. available arguments. Flask-specific behavior is listed here.
  1662. :param path: URL path being requested.
  1663. :param base_url: Base URL where the app is being served, which
  1664. ``path`` is relative to. If not given, built from
  1665. :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
  1666. :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
  1667. :param subdomain: Subdomain name to append to
  1668. :data:`SERVER_NAME`.
  1669. :param url_scheme: Scheme to use instead of
  1670. :data:`PREFERRED_URL_SCHEME`.
  1671. :param data: The request body, either as a string or a dict of
  1672. form keys and values.
  1673. :param json: If given, this is serialized as JSON and passed as
  1674. ``data``. Also defaults ``content_type`` to
  1675. ``application/json``.
  1676. :param args: other positional arguments passed to
  1677. :class:`~werkzeug.test.EnvironBuilder`.
  1678. :param kwargs: other keyword arguments passed to
  1679. :class:`~werkzeug.test.EnvironBuilder`.
  1680. """
  1681. from .testing import EnvironBuilder
  1682. builder = EnvironBuilder(self, *args, **kwargs)
  1683. try:
  1684. return self.request_context(builder.get_environ())
  1685. finally:
  1686. builder.close()
  1687. def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:
  1688. """The actual WSGI application. This is not implemented in
  1689. :meth:`__call__` so that middlewares can be applied without
  1690. losing a reference to the app object. Instead of doing this::
  1691. app = MyMiddleware(app)
  1692. It's a better idea to do this instead::
  1693. app.wsgi_app = MyMiddleware(app.wsgi_app)
  1694. Then you still have the original application object around and
  1695. can continue to call methods on it.
  1696. .. versionchanged:: 0.7
  1697. Teardown events for the request and app contexts are called
  1698. even if an unhandled error occurs. Other events may not be
  1699. called depending on when an error occurs during dispatch.
  1700. See :ref:`callbacks-and-errors`.
  1701. :param environ: A WSGI environment.
  1702. :param start_response: A callable accepting a status code,
  1703. a list of headers, and an optional exception context to
  1704. start the response.
  1705. """
  1706. ctx = self.request_context(environ)
  1707. error: t.Optional[BaseException] = None
  1708. try:
  1709. try:
  1710. ctx.push()
  1711. response = self.full_dispatch_request()
  1712. except Exception as e:
  1713. error = e
  1714. response = self.handle_exception(e)
  1715. except: # noqa: B001
  1716. error = sys.exc_info()[1]
  1717. raise
  1718. return response(environ, start_response)
  1719. finally:
  1720. if self.should_ignore_error(error):
  1721. error = None
  1722. ctx.auto_pop(error)
  1723. def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:
  1724. """The WSGI server calls the Flask application object as the
  1725. WSGI application. This calls :meth:`wsgi_app`, which can be
  1726. wrapped to apply middleware.
  1727. """
  1728. return self.wsgi_app(environ, start_response)