app.py 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498
  1. from __future__ import annotations
  2. import collections.abc as cabc
  3. import os
  4. import sys
  5. import typing as t
  6. import weakref
  7. from datetime import timedelta
  8. from inspect import iscoroutinefunction
  9. from itertools import chain
  10. from types import TracebackType
  11. from urllib.parse import quote as _url_quote
  12. import click
  13. from werkzeug.datastructures import Headers
  14. from werkzeug.datastructures import ImmutableDict
  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 MapAdapter
  20. from werkzeug.routing import RequestRedirect
  21. from werkzeug.routing import RoutingException
  22. from werkzeug.routing import Rule
  23. from werkzeug.serving import is_running_from_reloader
  24. from werkzeug.wrappers import Response as BaseResponse
  25. from . import cli
  26. from . import typing as ft
  27. from .ctx import AppContext
  28. from .ctx import RequestContext
  29. from .globals import _cv_app
  30. from .globals import _cv_request
  31. from .globals import current_app
  32. from .globals import g
  33. from .globals import request
  34. from .globals import request_ctx
  35. from .globals import session
  36. from .helpers import get_debug_flag
  37. from .helpers import get_flashed_messages
  38. from .helpers import get_load_dotenv
  39. from .helpers import send_from_directory
  40. from .sansio.app import App
  41. from .sansio.scaffold import _sentinel
  42. from .sessions import SecureCookieSessionInterface
  43. from .sessions import SessionInterface
  44. from .signals import appcontext_tearing_down
  45. from .signals import got_request_exception
  46. from .signals import request_finished
  47. from .signals import request_started
  48. from .signals import request_tearing_down
  49. from .templating import Environment
  50. from .wrappers import Request
  51. from .wrappers import Response
  52. if t.TYPE_CHECKING: # pragma: no cover
  53. from _typeshed.wsgi import StartResponse
  54. from _typeshed.wsgi import WSGIEnvironment
  55. from .testing import FlaskClient
  56. from .testing import FlaskCliRunner
  57. T_shell_context_processor = t.TypeVar(
  58. "T_shell_context_processor", bound=ft.ShellContextProcessorCallable
  59. )
  60. T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)
  61. T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)
  62. T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)
  63. T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)
  64. def _make_timedelta(value: timedelta | int | None) -> timedelta | None:
  65. if value is None or isinstance(value, timedelta):
  66. return value
  67. return timedelta(seconds=value)
  68. class Flask(App):
  69. """The flask object implements a WSGI application and acts as the central
  70. object. It is passed the name of the module or package of the
  71. application. Once it is created it will act as a central registry for
  72. the view functions, the URL rules, template configuration and much more.
  73. The name of the package is used to resolve resources from inside the
  74. package or the folder the module is contained in depending on if the
  75. package parameter resolves to an actual python package (a folder with
  76. an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).
  77. For more information about resource loading, see :func:`open_resource`.
  78. Usually you create a :class:`Flask` instance in your main module or
  79. in the :file:`__init__.py` file of your package like this::
  80. from flask import Flask
  81. app = Flask(__name__)
  82. .. admonition:: About the First Parameter
  83. The idea of the first parameter is to give Flask an idea of what
  84. belongs to your application. This name is used to find resources
  85. on the filesystem, can be used by extensions to improve debugging
  86. information and a lot more.
  87. So it's important what you provide there. If you are using a single
  88. module, `__name__` is always the correct value. If you however are
  89. using a package, it's usually recommended to hardcode the name of
  90. your package there.
  91. For example if your application is defined in :file:`yourapplication/app.py`
  92. you should create it with one of the two versions below::
  93. app = Flask('yourapplication')
  94. app = Flask(__name__.split('.')[0])
  95. Why is that? The application will work even with `__name__`, thanks
  96. to how resources are looked up. However it will make debugging more
  97. painful. Certain extensions can make assumptions based on the
  98. import name of your application. For example the Flask-SQLAlchemy
  99. extension will look for the code in your application that triggered
  100. an SQL query in debug mode. If the import name is not properly set
  101. up, that debugging information is lost. (For example it would only
  102. pick up SQL queries in `yourapplication.app` and not
  103. `yourapplication.views.frontend`)
  104. .. versionadded:: 0.7
  105. The `static_url_path`, `static_folder`, and `template_folder`
  106. parameters were added.
  107. .. versionadded:: 0.8
  108. The `instance_path` and `instance_relative_config` parameters were
  109. added.
  110. .. versionadded:: 0.11
  111. The `root_path` parameter was added.
  112. .. versionadded:: 1.0
  113. The ``host_matching`` and ``static_host`` parameters were added.
  114. .. versionadded:: 1.0
  115. The ``subdomain_matching`` parameter was added. Subdomain
  116. matching needs to be enabled manually now. Setting
  117. :data:`SERVER_NAME` does not implicitly enable it.
  118. :param import_name: the name of the application package
  119. :param static_url_path: can be used to specify a different path for the
  120. static files on the web. Defaults to the name
  121. of the `static_folder` folder.
  122. :param static_folder: The folder with static files that is served at
  123. ``static_url_path``. Relative to the application ``root_path``
  124. or an absolute path. Defaults to ``'static'``.
  125. :param static_host: the host to use when adding the static route.
  126. Defaults to None. Required when using ``host_matching=True``
  127. with a ``static_folder`` configured.
  128. :param host_matching: set ``url_map.host_matching`` attribute.
  129. Defaults to False.
  130. :param subdomain_matching: consider the subdomain relative to
  131. :data:`SERVER_NAME` when matching routes. Defaults to False.
  132. :param template_folder: the folder that contains the templates that should
  133. be used by the application. Defaults to
  134. ``'templates'`` folder in the root path of the
  135. application.
  136. :param instance_path: An alternative instance path for the application.
  137. By default the folder ``'instance'`` next to the
  138. package or module is assumed to be the instance
  139. path.
  140. :param instance_relative_config: if set to ``True`` relative filenames
  141. for loading the config are assumed to
  142. be relative to the instance path instead
  143. of the application root.
  144. :param root_path: The path to the root of the application files.
  145. This should only be set manually when it can't be detected
  146. automatically, such as for namespace packages.
  147. """
  148. default_config = ImmutableDict(
  149. {
  150. "DEBUG": None,
  151. "TESTING": False,
  152. "PROPAGATE_EXCEPTIONS": None,
  153. "SECRET_KEY": None,
  154. "PERMANENT_SESSION_LIFETIME": timedelta(days=31),
  155. "USE_X_SENDFILE": False,
  156. "SERVER_NAME": None,
  157. "APPLICATION_ROOT": "/",
  158. "SESSION_COOKIE_NAME": "session",
  159. "SESSION_COOKIE_DOMAIN": None,
  160. "SESSION_COOKIE_PATH": None,
  161. "SESSION_COOKIE_HTTPONLY": True,
  162. "SESSION_COOKIE_SECURE": False,
  163. "SESSION_COOKIE_SAMESITE": None,
  164. "SESSION_REFRESH_EACH_REQUEST": True,
  165. "MAX_CONTENT_LENGTH": None,
  166. "SEND_FILE_MAX_AGE_DEFAULT": None,
  167. "TRAP_BAD_REQUEST_ERRORS": None,
  168. "TRAP_HTTP_EXCEPTIONS": False,
  169. "EXPLAIN_TEMPLATE_LOADING": False,
  170. "PREFERRED_URL_SCHEME": "http",
  171. "TEMPLATES_AUTO_RELOAD": None,
  172. "MAX_COOKIE_SIZE": 4093,
  173. }
  174. )
  175. #: The class that is used for request objects. See :class:`~flask.Request`
  176. #: for more information.
  177. request_class: type[Request] = Request
  178. #: The class that is used for response objects. See
  179. #: :class:`~flask.Response` for more information.
  180. response_class: type[Response] = Response
  181. #: the session interface to use. By default an instance of
  182. #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.
  183. #:
  184. #: .. versionadded:: 0.8
  185. session_interface: SessionInterface = SecureCookieSessionInterface()
  186. def __init__(
  187. self,
  188. import_name: str,
  189. static_url_path: str | None = None,
  190. static_folder: str | os.PathLike[str] | None = "static",
  191. static_host: str | None = None,
  192. host_matching: bool = False,
  193. subdomain_matching: bool = False,
  194. template_folder: str | os.PathLike[str] | None = "templates",
  195. instance_path: str | None = None,
  196. instance_relative_config: bool = False,
  197. root_path: str | None = None,
  198. ):
  199. super().__init__(
  200. import_name=import_name,
  201. static_url_path=static_url_path,
  202. static_folder=static_folder,
  203. static_host=static_host,
  204. host_matching=host_matching,
  205. subdomain_matching=subdomain_matching,
  206. template_folder=template_folder,
  207. instance_path=instance_path,
  208. instance_relative_config=instance_relative_config,
  209. root_path=root_path,
  210. )
  211. #: The Click command group for registering CLI commands for this
  212. #: object. The commands are available from the ``flask`` command
  213. #: once the application has been discovered and blueprints have
  214. #: been registered.
  215. self.cli = cli.AppGroup()
  216. # Set the name of the Click group in case someone wants to add
  217. # the app's commands to another CLI tool.
  218. self.cli.name = self.name
  219. # Add a static route using the provided static_url_path, static_host,
  220. # and static_folder if there is a configured static_folder.
  221. # Note we do this without checking if static_folder exists.
  222. # For one, it might be created while the server is running (e.g. during
  223. # development). Also, Google App Engine stores static files somewhere
  224. if self.has_static_folder:
  225. assert (
  226. bool(static_host) == host_matching
  227. ), "Invalid static_host/host_matching combination"
  228. # Use a weakref to avoid creating a reference cycle between the app
  229. # and the view function (see #3761).
  230. self_ref = weakref.ref(self)
  231. self.add_url_rule(
  232. f"{self.static_url_path}/<path:filename>",
  233. endpoint="static",
  234. host=static_host,
  235. view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950
  236. )
  237. def get_send_file_max_age(self, filename: str | None) -> int | None:
  238. """Used by :func:`send_file` to determine the ``max_age`` cache
  239. value for a given file path if it wasn't passed.
  240. By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from
  241. the configuration of :data:`~flask.current_app`. This defaults
  242. to ``None``, which tells the browser to use conditional requests
  243. instead of a timed cache, which is usually preferable.
  244. Note this is a duplicate of the same method in the Flask
  245. class.
  246. .. versionchanged:: 2.0
  247. The default configuration is ``None`` instead of 12 hours.
  248. .. versionadded:: 0.9
  249. """
  250. value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]
  251. if value is None:
  252. return None
  253. if isinstance(value, timedelta):
  254. return int(value.total_seconds())
  255. return value # type: ignore[no-any-return]
  256. def send_static_file(self, filename: str) -> Response:
  257. """The view function used to serve files from
  258. :attr:`static_folder`. A route is automatically registered for
  259. this view at :attr:`static_url_path` if :attr:`static_folder` is
  260. set.
  261. Note this is a duplicate of the same method in the Flask
  262. class.
  263. .. versionadded:: 0.5
  264. """
  265. if not self.has_static_folder:
  266. raise RuntimeError("'static_folder' must be set to serve static_files.")
  267. # send_file only knows to call get_send_file_max_age on the app,
  268. # call it here so it works for blueprints too.
  269. max_age = self.get_send_file_max_age(filename)
  270. return send_from_directory(
  271. t.cast(str, self.static_folder), filename, max_age=max_age
  272. )
  273. def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
  274. """Open a resource file relative to :attr:`root_path` for
  275. reading.
  276. For example, if the file ``schema.sql`` is next to the file
  277. ``app.py`` where the ``Flask`` app is defined, it can be opened
  278. with:
  279. .. code-block:: python
  280. with app.open_resource("schema.sql") as f:
  281. conn.executescript(f.read())
  282. :param resource: Path to the resource relative to
  283. :attr:`root_path`.
  284. :param mode: Open the file in this mode. Only reading is
  285. supported, valid values are "r" (or "rt") and "rb".
  286. Note this is a duplicate of the same method in the Flask
  287. class.
  288. """
  289. if mode not in {"r", "rt", "rb"}:
  290. raise ValueError("Resources can only be opened for reading.")
  291. return open(os.path.join(self.root_path, resource), mode)
  292. def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:
  293. """Opens a resource from the application's instance folder
  294. (:attr:`instance_path`). Otherwise works like
  295. :meth:`open_resource`. Instance resources can also be opened for
  296. writing.
  297. :param resource: the name of the resource. To access resources within
  298. subfolders use forward slashes as separator.
  299. :param mode: resource file opening mode, default is 'rb'.
  300. """
  301. return open(os.path.join(self.instance_path, resource), mode)
  302. def create_jinja_environment(self) -> Environment:
  303. """Create the Jinja environment based on :attr:`jinja_options`
  304. and the various Jinja-related methods of the app. Changing
  305. :attr:`jinja_options` after this will have no effect. Also adds
  306. Flask-related globals and filters to the environment.
  307. .. versionchanged:: 0.11
  308. ``Environment.auto_reload`` set in accordance with
  309. ``TEMPLATES_AUTO_RELOAD`` configuration option.
  310. .. versionadded:: 0.5
  311. """
  312. options = dict(self.jinja_options)
  313. if "autoescape" not in options:
  314. options["autoescape"] = self.select_jinja_autoescape
  315. if "auto_reload" not in options:
  316. auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]
  317. if auto_reload is None:
  318. auto_reload = self.debug
  319. options["auto_reload"] = auto_reload
  320. rv = self.jinja_environment(self, **options)
  321. rv.globals.update(
  322. url_for=self.url_for,
  323. get_flashed_messages=get_flashed_messages,
  324. config=self.config,
  325. # request, session and g are normally added with the
  326. # context processor for efficiency reasons but for imported
  327. # templates we also want the proxies in there.
  328. request=request,
  329. session=session,
  330. g=g,
  331. )
  332. rv.policies["json.dumps_function"] = self.json.dumps
  333. return rv
  334. def create_url_adapter(self, request: Request | None) -> MapAdapter | None:
  335. """Creates a URL adapter for the given request. The URL adapter
  336. is created at a point where the request context is not yet set
  337. up so the request is passed explicitly.
  338. .. versionadded:: 0.6
  339. .. versionchanged:: 0.9
  340. This can now also be called without a request object when the
  341. URL adapter is created for the application context.
  342. .. versionchanged:: 1.0
  343. :data:`SERVER_NAME` no longer implicitly enables subdomain
  344. matching. Use :attr:`subdomain_matching` instead.
  345. """
  346. if request is not None:
  347. # If subdomain matching is disabled (the default), use the
  348. # default subdomain in all cases. This should be the default
  349. # in Werkzeug but it currently does not have that feature.
  350. if not self.subdomain_matching:
  351. subdomain = self.url_map.default_subdomain or None
  352. else:
  353. subdomain = None
  354. return self.url_map.bind_to_environ(
  355. request.environ,
  356. server_name=self.config["SERVER_NAME"],
  357. subdomain=subdomain,
  358. )
  359. # We need at the very least the server name to be set for this
  360. # to work.
  361. if self.config["SERVER_NAME"] is not None:
  362. return self.url_map.bind(
  363. self.config["SERVER_NAME"],
  364. script_name=self.config["APPLICATION_ROOT"],
  365. url_scheme=self.config["PREFERRED_URL_SCHEME"],
  366. )
  367. return None
  368. def raise_routing_exception(self, request: Request) -> t.NoReturn:
  369. """Intercept routing exceptions and possibly do something else.
  370. In debug mode, intercept a routing redirect and replace it with
  371. an error if the body will be discarded.
  372. With modern Werkzeug this shouldn't occur, since it now uses a
  373. 308 status which tells the browser to resend the method and
  374. body.
  375. .. versionchanged:: 2.1
  376. Don't intercept 307 and 308 redirects.
  377. :meta private:
  378. :internal:
  379. """
  380. if (
  381. not self.debug
  382. or not isinstance(request.routing_exception, RequestRedirect)
  383. or request.routing_exception.code in {307, 308}
  384. or request.method in {"GET", "HEAD", "OPTIONS"}
  385. ):
  386. raise request.routing_exception # type: ignore[misc]
  387. from .debughelpers import FormDataRoutingRedirect
  388. raise FormDataRoutingRedirect(request)
  389. def update_template_context(self, context: dict[str, t.Any]) -> None:
  390. """Update the template context with some commonly used variables.
  391. This injects request, session, config and g into the template
  392. context as well as everything template context processors want
  393. to inject. Note that the as of Flask 0.6, the original values
  394. in the context will not be overridden if a context processor
  395. decides to return a value with the same key.
  396. :param context: the context as a dictionary that is updated in place
  397. to add extra variables.
  398. """
  399. names: t.Iterable[str | None] = (None,)
  400. # A template may be rendered outside a request context.
  401. if request:
  402. names = chain(names, reversed(request.blueprints))
  403. # The values passed to render_template take precedence. Keep a
  404. # copy to re-apply after all context functions.
  405. orig_ctx = context.copy()
  406. for name in names:
  407. if name in self.template_context_processors:
  408. for func in self.template_context_processors[name]:
  409. context.update(self.ensure_sync(func)())
  410. context.update(orig_ctx)
  411. def make_shell_context(self) -> dict[str, t.Any]:
  412. """Returns the shell context for an interactive shell for this
  413. application. This runs all the registered shell context
  414. processors.
  415. .. versionadded:: 0.11
  416. """
  417. rv = {"app": self, "g": g}
  418. for processor in self.shell_context_processors:
  419. rv.update(processor())
  420. return rv
  421. def run(
  422. self,
  423. host: str | None = None,
  424. port: int | None = None,
  425. debug: bool | None = None,
  426. load_dotenv: bool = True,
  427. **options: t.Any,
  428. ) -> None:
  429. """Runs the application on a local development server.
  430. Do not use ``run()`` in a production setting. It is not intended to
  431. meet security and performance requirements for a production server.
  432. Instead, see :doc:`/deploying/index` for WSGI server recommendations.
  433. If the :attr:`debug` flag is set the server will automatically reload
  434. for code changes and show a debugger in case an exception happened.
  435. If you want to run the application in debug mode, but disable the
  436. code execution on the interactive debugger, you can pass
  437. ``use_evalex=False`` as parameter. This will keep the debugger's
  438. traceback screen active, but disable code execution.
  439. It is not recommended to use this function for development with
  440. automatic reloading as this is badly supported. Instead you should
  441. be using the :command:`flask` command line script's ``run`` support.
  442. .. admonition:: Keep in Mind
  443. Flask will suppress any server error with a generic error page
  444. unless it is in debug mode. As such to enable just the
  445. interactive debugger without the code reloading, you have to
  446. invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.
  447. Setting ``use_debugger`` to ``True`` without being in debug mode
  448. won't catch any exceptions because there won't be any to
  449. catch.
  450. :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to
  451. have the server available externally as well. Defaults to
  452. ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable
  453. if present.
  454. :param port: the port of the webserver. Defaults to ``5000`` or the
  455. port defined in the ``SERVER_NAME`` config variable if present.
  456. :param debug: if given, enable or disable debug mode. See
  457. :attr:`debug`.
  458. :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`
  459. files to set environment variables. Will also change the working
  460. directory to the directory containing the first file found.
  461. :param options: the options to be forwarded to the underlying Werkzeug
  462. server. See :func:`werkzeug.serving.run_simple` for more
  463. information.
  464. .. versionchanged:: 1.0
  465. If installed, python-dotenv will be used to load environment
  466. variables from :file:`.env` and :file:`.flaskenv` files.
  467. The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.
  468. Threaded mode is enabled by default.
  469. .. versionchanged:: 0.10
  470. The default port is now picked from the ``SERVER_NAME``
  471. variable.
  472. """
  473. # Ignore this call so that it doesn't start another server if
  474. # the 'flask run' command is used.
  475. if os.environ.get("FLASK_RUN_FROM_CLI") == "true":
  476. if not is_running_from_reloader():
  477. click.secho(
  478. " * Ignoring a call to 'app.run()' that would block"
  479. " the current 'flask' CLI command.\n"
  480. " Only call 'app.run()' in an 'if __name__ =="
  481. ' "__main__"\' guard.',
  482. fg="red",
  483. )
  484. return
  485. if get_load_dotenv(load_dotenv):
  486. cli.load_dotenv()
  487. # if set, env var overrides existing value
  488. if "FLASK_DEBUG" in os.environ:
  489. self.debug = get_debug_flag()
  490. # debug passed to method overrides all other sources
  491. if debug is not None:
  492. self.debug = bool(debug)
  493. server_name = self.config.get("SERVER_NAME")
  494. sn_host = sn_port = None
  495. if server_name:
  496. sn_host, _, sn_port = server_name.partition(":")
  497. if not host:
  498. if sn_host:
  499. host = sn_host
  500. else:
  501. host = "127.0.0.1"
  502. if port or port == 0:
  503. port = int(port)
  504. elif sn_port:
  505. port = int(sn_port)
  506. else:
  507. port = 5000
  508. options.setdefault("use_reloader", self.debug)
  509. options.setdefault("use_debugger", self.debug)
  510. options.setdefault("threaded", True)
  511. cli.show_server_banner(self.debug, self.name)
  512. from werkzeug.serving import run_simple
  513. try:
  514. run_simple(t.cast(str, host), port, self, **options)
  515. finally:
  516. # reset the first request information if the development server
  517. # reset normally. This makes it possible to restart the server
  518. # without reloader and that stuff from an interactive shell.
  519. self._got_first_request = False
  520. def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:
  521. """Creates a test client for this application. For information
  522. about unit testing head over to :doc:`/testing`.
  523. Note that if you are testing for assertions or exceptions in your
  524. application code, you must set ``app.testing = True`` in order for the
  525. exceptions to propagate to the test client. Otherwise, the exception
  526. will be handled by the application (not visible to the test client) and
  527. the only indication of an AssertionError or other exception will be a
  528. 500 status code response to the test client. See the :attr:`testing`
  529. attribute. For example::
  530. app.testing = True
  531. client = app.test_client()
  532. The test client can be used in a ``with`` block to defer the closing down
  533. of the context until the end of the ``with`` block. This is useful if
  534. you want to access the context locals for testing::
  535. with app.test_client() as c:
  536. rv = c.get('/?vodka=42')
  537. assert request.args['vodka'] == '42'
  538. Additionally, you may pass optional keyword arguments that will then
  539. be passed to the application's :attr:`test_client_class` constructor.
  540. For example::
  541. from flask.testing import FlaskClient
  542. class CustomClient(FlaskClient):
  543. def __init__(self, *args, **kwargs):
  544. self._authentication = kwargs.pop("authentication")
  545. super(CustomClient,self).__init__( *args, **kwargs)
  546. app.test_client_class = CustomClient
  547. client = app.test_client(authentication='Basic ....')
  548. See :class:`~flask.testing.FlaskClient` for more information.
  549. .. versionchanged:: 0.4
  550. added support for ``with`` block usage for the client.
  551. .. versionadded:: 0.7
  552. The `use_cookies` parameter was added as well as the ability
  553. to override the client to be used by setting the
  554. :attr:`test_client_class` attribute.
  555. .. versionchanged:: 0.11
  556. Added `**kwargs` to support passing additional keyword arguments to
  557. the constructor of :attr:`test_client_class`.
  558. """
  559. cls = self.test_client_class
  560. if cls is None:
  561. from .testing import FlaskClient as cls
  562. return cls( # type: ignore
  563. self, self.response_class, use_cookies=use_cookies, **kwargs
  564. )
  565. def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:
  566. """Create a CLI runner for testing CLI commands.
  567. See :ref:`testing-cli`.
  568. Returns an instance of :attr:`test_cli_runner_class`, by default
  569. :class:`~flask.testing.FlaskCliRunner`. The Flask app object is
  570. passed as the first argument.
  571. .. versionadded:: 1.0
  572. """
  573. cls = self.test_cli_runner_class
  574. if cls is None:
  575. from .testing import FlaskCliRunner as cls
  576. return cls(self, **kwargs) # type: ignore
  577. def handle_http_exception(
  578. self, e: HTTPException
  579. ) -> HTTPException | ft.ResponseReturnValue:
  580. """Handles an HTTP exception. By default this will invoke the
  581. registered error handlers and fall back to returning the
  582. exception as response.
  583. .. versionchanged:: 1.0.3
  584. ``RoutingException``, used internally for actions such as
  585. slash redirects during routing, is not passed to error
  586. handlers.
  587. .. versionchanged:: 1.0
  588. Exceptions are looked up by code *and* by MRO, so
  589. ``HTTPException`` subclasses can be handled with a catch-all
  590. handler for the base ``HTTPException``.
  591. .. versionadded:: 0.3
  592. """
  593. # Proxy exceptions don't have error codes. We want to always return
  594. # those unchanged as errors
  595. if e.code is None:
  596. return e
  597. # RoutingExceptions are used internally to trigger routing
  598. # actions, such as slash redirects raising RequestRedirect. They
  599. # are not raised or handled in user code.
  600. if isinstance(e, RoutingException):
  601. return e
  602. handler = self._find_error_handler(e, request.blueprints)
  603. if handler is None:
  604. return e
  605. return self.ensure_sync(handler)(e) # type: ignore[no-any-return]
  606. def handle_user_exception(
  607. self, e: Exception
  608. ) -> HTTPException | ft.ResponseReturnValue:
  609. """This method is called whenever an exception occurs that
  610. should be handled. A special case is :class:`~werkzeug
  611. .exceptions.HTTPException` which is forwarded to the
  612. :meth:`handle_http_exception` method. This function will either
  613. return a response value or reraise the exception with the same
  614. traceback.
  615. .. versionchanged:: 1.0
  616. Key errors raised from request data like ``form`` show the
  617. bad key in debug mode rather than a generic bad request
  618. message.
  619. .. versionadded:: 0.7
  620. """
  621. if isinstance(e, BadRequestKeyError) and (
  622. self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]
  623. ):
  624. e.show_exception = True
  625. if isinstance(e, HTTPException) and not self.trap_http_exception(e):
  626. return self.handle_http_exception(e)
  627. handler = self._find_error_handler(e, request.blueprints)
  628. if handler is None:
  629. raise
  630. return self.ensure_sync(handler)(e) # type: ignore[no-any-return]
  631. def handle_exception(self, e: Exception) -> Response:
  632. """Handle an exception that did not have an error handler
  633. associated with it, or that was raised from an error handler.
  634. This always causes a 500 ``InternalServerError``.
  635. Always sends the :data:`got_request_exception` signal.
  636. If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug
  637. mode, the error will be re-raised so that the debugger can
  638. display it. Otherwise, the original exception is logged, and
  639. an :exc:`~werkzeug.exceptions.InternalServerError` is returned.
  640. If an error handler is registered for ``InternalServerError`` or
  641. ``500``, it will be used. For consistency, the handler will
  642. always receive the ``InternalServerError``. The original
  643. unhandled exception is available as ``e.original_exception``.
  644. .. versionchanged:: 1.1.0
  645. Always passes the ``InternalServerError`` instance to the
  646. handler, setting ``original_exception`` to the unhandled
  647. error.
  648. .. versionchanged:: 1.1.0
  649. ``after_request`` functions and other finalization is done
  650. even for the default 500 response when there is no handler.
  651. .. versionadded:: 0.3
  652. """
  653. exc_info = sys.exc_info()
  654. got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)
  655. propagate = self.config["PROPAGATE_EXCEPTIONS"]
  656. if propagate is None:
  657. propagate = self.testing or self.debug
  658. if propagate:
  659. # Re-raise if called with an active exception, otherwise
  660. # raise the passed in exception.
  661. if exc_info[1] is e:
  662. raise
  663. raise e
  664. self.log_exception(exc_info)
  665. server_error: InternalServerError | ft.ResponseReturnValue
  666. server_error = InternalServerError(original_exception=e)
  667. handler = self._find_error_handler(server_error, request.blueprints)
  668. if handler is not None:
  669. server_error = self.ensure_sync(handler)(server_error)
  670. return self.finalize_request(server_error, from_error_handler=True)
  671. def log_exception(
  672. self,
  673. exc_info: (tuple[type, BaseException, TracebackType] | tuple[None, None, None]),
  674. ) -> None:
  675. """Logs an exception. This is called by :meth:`handle_exception`
  676. if debugging is disabled and right before the handler is called.
  677. The default implementation logs the exception as error on the
  678. :attr:`logger`.
  679. .. versionadded:: 0.8
  680. """
  681. self.logger.error(
  682. f"Exception on {request.path} [{request.method}]", exc_info=exc_info
  683. )
  684. def dispatch_request(self) -> ft.ResponseReturnValue:
  685. """Does the request dispatching. Matches the URL and returns the
  686. return value of the view or error handler. This does not have to
  687. be a response object. In order to convert the return value to a
  688. proper response object, call :func:`make_response`.
  689. .. versionchanged:: 0.7
  690. This no longer does the exception handling, this code was
  691. moved to the new :meth:`full_dispatch_request`.
  692. """
  693. req = request_ctx.request
  694. if req.routing_exception is not None:
  695. self.raise_routing_exception(req)
  696. rule: Rule = req.url_rule # type: ignore[assignment]
  697. # if we provide automatic options for this URL and the
  698. # request came with the OPTIONS method, reply automatically
  699. if (
  700. getattr(rule, "provide_automatic_options", False)
  701. and req.method == "OPTIONS"
  702. ):
  703. return self.make_default_options_response()
  704. # otherwise dispatch to the handler for that endpoint
  705. view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]
  706. return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args) # type: ignore[no-any-return]
  707. def full_dispatch_request(self) -> Response:
  708. """Dispatches the request and on top of that performs request
  709. pre and postprocessing as well as HTTP exception catching and
  710. error handling.
  711. .. versionadded:: 0.7
  712. """
  713. self._got_first_request = True
  714. try:
  715. request_started.send(self, _async_wrapper=self.ensure_sync)
  716. rv = self.preprocess_request()
  717. if rv is None:
  718. rv = self.dispatch_request()
  719. except Exception as e:
  720. rv = self.handle_user_exception(e)
  721. return self.finalize_request(rv)
  722. def finalize_request(
  723. self,
  724. rv: ft.ResponseReturnValue | HTTPException,
  725. from_error_handler: bool = False,
  726. ) -> Response:
  727. """Given the return value from a view function this finalizes
  728. the request by converting it into a response and invoking the
  729. postprocessing functions. This is invoked for both normal
  730. request dispatching as well as error handlers.
  731. Because this means that it might be called as a result of a
  732. failure a special safe mode is available which can be enabled
  733. with the `from_error_handler` flag. If enabled, failures in
  734. response processing will be logged and otherwise ignored.
  735. :internal:
  736. """
  737. response = self.make_response(rv)
  738. try:
  739. response = self.process_response(response)
  740. request_finished.send(
  741. self, _async_wrapper=self.ensure_sync, response=response
  742. )
  743. except Exception:
  744. if not from_error_handler:
  745. raise
  746. self.logger.exception(
  747. "Request finalizing failed with an error while handling an error"
  748. )
  749. return response
  750. def make_default_options_response(self) -> Response:
  751. """This method is called to create the default ``OPTIONS`` response.
  752. This can be changed through subclassing to change the default
  753. behavior of ``OPTIONS`` responses.
  754. .. versionadded:: 0.7
  755. """
  756. adapter = request_ctx.url_adapter
  757. methods = adapter.allowed_methods() # type: ignore[union-attr]
  758. rv = self.response_class()
  759. rv.allow.update(methods)
  760. return rv
  761. def ensure_sync(self, func: t.Callable[..., t.Any]) -> t.Callable[..., t.Any]:
  762. """Ensure that the function is synchronous for WSGI workers.
  763. Plain ``def`` functions are returned as-is. ``async def``
  764. functions are wrapped to run and wait for the response.
  765. Override this method to change how the app runs async views.
  766. .. versionadded:: 2.0
  767. """
  768. if iscoroutinefunction(func):
  769. return self.async_to_sync(func)
  770. return func
  771. def async_to_sync(
  772. self, func: t.Callable[..., t.Coroutine[t.Any, t.Any, t.Any]]
  773. ) -> t.Callable[..., t.Any]:
  774. """Return a sync function that will run the coroutine function.
  775. .. code-block:: python
  776. result = app.async_to_sync(func)(*args, **kwargs)
  777. Override this method to change how the app converts async code
  778. to be synchronously callable.
  779. .. versionadded:: 2.0
  780. """
  781. try:
  782. from asgiref.sync import async_to_sync as asgiref_async_to_sync
  783. except ImportError:
  784. raise RuntimeError(
  785. "Install Flask with the 'async' extra in order to use async views."
  786. ) from None
  787. return asgiref_async_to_sync(func)
  788. def url_for(
  789. self,
  790. /,
  791. endpoint: str,
  792. *,
  793. _anchor: str | None = None,
  794. _method: str | None = None,
  795. _scheme: str | None = None,
  796. _external: bool | None = None,
  797. **values: t.Any,
  798. ) -> str:
  799. """Generate a URL to the given endpoint with the given values.
  800. This is called by :func:`flask.url_for`, and can be called
  801. directly as well.
  802. An *endpoint* is the name of a URL rule, usually added with
  803. :meth:`@app.route() <route>`, and usually the same name as the
  804. view function. A route defined in a :class:`~flask.Blueprint`
  805. will prepend the blueprint's name separated by a ``.`` to the
  806. endpoint.
  807. In some cases, such as email messages, you want URLs to include
  808. the scheme and domain, like ``https://example.com/hello``. When
  809. not in an active request, URLs will be external by default, but
  810. this requires setting :data:`SERVER_NAME` so Flask knows what
  811. domain to use. :data:`APPLICATION_ROOT` and
  812. :data:`PREFERRED_URL_SCHEME` should also be configured as
  813. needed. This config is only used when not in an active request.
  814. Functions can be decorated with :meth:`url_defaults` to modify
  815. keyword arguments before the URL is built.
  816. If building fails for some reason, such as an unknown endpoint
  817. or incorrect values, the app's :meth:`handle_url_build_error`
  818. method is called. If that returns a string, that is returned,
  819. otherwise a :exc:`~werkzeug.routing.BuildError` is raised.
  820. :param endpoint: The endpoint name associated with the URL to
  821. generate. If this starts with a ``.``, the current blueprint
  822. name (if any) will be used.
  823. :param _anchor: If given, append this as ``#anchor`` to the URL.
  824. :param _method: If given, generate the URL associated with this
  825. method for the endpoint.
  826. :param _scheme: If given, the URL will have this scheme if it
  827. is external.
  828. :param _external: If given, prefer the URL to be internal
  829. (False) or require it to be external (True). External URLs
  830. include the scheme and domain. When not in an active
  831. request, URLs are external by default.
  832. :param values: Values to use for the variable parts of the URL
  833. rule. Unknown keys are appended as query string arguments,
  834. like ``?a=b&c=d``.
  835. .. versionadded:: 2.2
  836. Moved from ``flask.url_for``, which calls this method.
  837. """
  838. req_ctx = _cv_request.get(None)
  839. if req_ctx is not None:
  840. url_adapter = req_ctx.url_adapter
  841. blueprint_name = req_ctx.request.blueprint
  842. # If the endpoint starts with "." and the request matches a
  843. # blueprint, the endpoint is relative to the blueprint.
  844. if endpoint[:1] == ".":
  845. if blueprint_name is not None:
  846. endpoint = f"{blueprint_name}{endpoint}"
  847. else:
  848. endpoint = endpoint[1:]
  849. # When in a request, generate a URL without scheme and
  850. # domain by default, unless a scheme is given.
  851. if _external is None:
  852. _external = _scheme is not None
  853. else:
  854. app_ctx = _cv_app.get(None)
  855. # If called by helpers.url_for, an app context is active,
  856. # use its url_adapter. Otherwise, app.url_for was called
  857. # directly, build an adapter.
  858. if app_ctx is not None:
  859. url_adapter = app_ctx.url_adapter
  860. else:
  861. url_adapter = self.create_url_adapter(None)
  862. if url_adapter is None:
  863. raise RuntimeError(
  864. "Unable to build URLs outside an active request"
  865. " without 'SERVER_NAME' configured. Also configure"
  866. " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as"
  867. " needed."
  868. )
  869. # When outside a request, generate a URL with scheme and
  870. # domain by default.
  871. if _external is None:
  872. _external = True
  873. # It is an error to set _scheme when _external=False, in order
  874. # to avoid accidental insecure URLs.
  875. if _scheme is not None and not _external:
  876. raise ValueError("When specifying '_scheme', '_external' must be True.")
  877. self.inject_url_defaults(endpoint, values)
  878. try:
  879. rv = url_adapter.build( # type: ignore[union-attr]
  880. endpoint,
  881. values,
  882. method=_method,
  883. url_scheme=_scheme,
  884. force_external=_external,
  885. )
  886. except BuildError as error:
  887. values.update(
  888. _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external
  889. )
  890. return self.handle_url_build_error(error, endpoint, values)
  891. if _anchor is not None:
  892. _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")
  893. rv = f"{rv}#{_anchor}"
  894. return rv
  895. def make_response(self, rv: ft.ResponseReturnValue) -> Response:
  896. """Convert the return value from a view function to an instance of
  897. :attr:`response_class`.
  898. :param rv: the return value from the view function. The view function
  899. must return a response. Returning ``None``, or the view ending
  900. without returning, is not allowed. The following types are allowed
  901. for ``view_rv``:
  902. ``str``
  903. A response object is created with the string encoded to UTF-8
  904. as the body.
  905. ``bytes``
  906. A response object is created with the bytes as the body.
  907. ``dict``
  908. A dictionary that will be jsonify'd before being returned.
  909. ``list``
  910. A list that will be jsonify'd before being returned.
  911. ``generator`` or ``iterator``
  912. A generator that returns ``str`` or ``bytes`` to be
  913. streamed as the response.
  914. ``tuple``
  915. Either ``(body, status, headers)``, ``(body, status)``, or
  916. ``(body, headers)``, where ``body`` is any of the other types
  917. allowed here, ``status`` is a string or an integer, and
  918. ``headers`` is a dictionary or a list of ``(key, value)``
  919. tuples. If ``body`` is a :attr:`response_class` instance,
  920. ``status`` overwrites the exiting value and ``headers`` are
  921. extended.
  922. :attr:`response_class`
  923. The object is returned unchanged.
  924. other :class:`~werkzeug.wrappers.Response` class
  925. The object is coerced to :attr:`response_class`.
  926. :func:`callable`
  927. The function is called as a WSGI application. The result is
  928. used to create a response object.
  929. .. versionchanged:: 2.2
  930. A generator will be converted to a streaming response.
  931. A list will be converted to a JSON response.
  932. .. versionchanged:: 1.1
  933. A dict will be converted to a JSON response.
  934. .. versionchanged:: 0.9
  935. Previously a tuple was interpreted as the arguments for the
  936. response object.
  937. """
  938. status = headers = None
  939. # unpack tuple returns
  940. if isinstance(rv, tuple):
  941. len_rv = len(rv)
  942. # a 3-tuple is unpacked directly
  943. if len_rv == 3:
  944. rv, status, headers = rv # type: ignore[misc]
  945. # decide if a 2-tuple has status or headers
  946. elif len_rv == 2:
  947. if isinstance(rv[1], (Headers, dict, tuple, list)):
  948. rv, headers = rv
  949. else:
  950. rv, status = rv # type: ignore[assignment,misc]
  951. # other sized tuples are not allowed
  952. else:
  953. raise TypeError(
  954. "The view function did not return a valid response tuple."
  955. " The tuple must have the form (body, status, headers),"
  956. " (body, status), or (body, headers)."
  957. )
  958. # the body must not be None
  959. if rv is None:
  960. raise TypeError(
  961. f"The view function for {request.endpoint!r} did not"
  962. " return a valid response. The function either returned"
  963. " None or ended without a return statement."
  964. )
  965. # make sure the body is an instance of the response class
  966. if not isinstance(rv, self.response_class):
  967. if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, cabc.Iterator):
  968. # let the response class set the status and headers instead of
  969. # waiting to do it manually, so that the class can handle any
  970. # special logic
  971. rv = self.response_class(
  972. rv,
  973. status=status,
  974. headers=headers, # type: ignore[arg-type]
  975. )
  976. status = headers = None
  977. elif isinstance(rv, (dict, list)):
  978. rv = self.json.response(rv)
  979. elif isinstance(rv, BaseResponse) or callable(rv):
  980. # evaluate a WSGI callable, or coerce a different response
  981. # class to the correct type
  982. try:
  983. rv = self.response_class.force_type(
  984. rv, # type: ignore[arg-type]
  985. request.environ,
  986. )
  987. except TypeError as e:
  988. raise TypeError(
  989. f"{e}\nThe view function did not return a valid"
  990. " response. The return type must be a string,"
  991. " dict, list, tuple with headers or status,"
  992. " Response instance, or WSGI callable, but it"
  993. f" was a {type(rv).__name__}."
  994. ).with_traceback(sys.exc_info()[2]) from None
  995. else:
  996. raise TypeError(
  997. "The view function did not return a valid"
  998. " response. The return type must be a string,"
  999. " dict, list, tuple with headers or status,"
  1000. " Response instance, or WSGI callable, but it was a"
  1001. f" {type(rv).__name__}."
  1002. )
  1003. rv = t.cast(Response, rv)
  1004. # prefer the status if it was provided
  1005. if status is not None:
  1006. if isinstance(status, (str, bytes, bytearray)):
  1007. rv.status = status
  1008. else:
  1009. rv.status_code = status
  1010. # extend existing headers with provided headers
  1011. if headers:
  1012. rv.headers.update(headers) # type: ignore[arg-type]
  1013. return rv
  1014. def preprocess_request(self) -> ft.ResponseReturnValue | None:
  1015. """Called before the request is dispatched. Calls
  1016. :attr:`url_value_preprocessors` registered with the app and the
  1017. current blueprint (if any). Then calls :attr:`before_request_funcs`
  1018. registered with the app and the blueprint.
  1019. If any :meth:`before_request` handler returns a non-None value, the
  1020. value is handled as if it was the return value from the view, and
  1021. further request handling is stopped.
  1022. """
  1023. names = (None, *reversed(request.blueprints))
  1024. for name in names:
  1025. if name in self.url_value_preprocessors:
  1026. for url_func in self.url_value_preprocessors[name]:
  1027. url_func(request.endpoint, request.view_args)
  1028. for name in names:
  1029. if name in self.before_request_funcs:
  1030. for before_func in self.before_request_funcs[name]:
  1031. rv = self.ensure_sync(before_func)()
  1032. if rv is not None:
  1033. return rv # type: ignore[no-any-return]
  1034. return None
  1035. def process_response(self, response: Response) -> Response:
  1036. """Can be overridden in order to modify the response object
  1037. before it's sent to the WSGI server. By default this will
  1038. call all the :meth:`after_request` decorated functions.
  1039. .. versionchanged:: 0.5
  1040. As of Flask 0.5 the functions registered for after request
  1041. execution are called in reverse order of registration.
  1042. :param response: a :attr:`response_class` object.
  1043. :return: a new response object or the same, has to be an
  1044. instance of :attr:`response_class`.
  1045. """
  1046. ctx = request_ctx._get_current_object() # type: ignore[attr-defined]
  1047. for func in ctx._after_request_functions:
  1048. response = self.ensure_sync(func)(response)
  1049. for name in chain(request.blueprints, (None,)):
  1050. if name in self.after_request_funcs:
  1051. for func in reversed(self.after_request_funcs[name]):
  1052. response = self.ensure_sync(func)(response)
  1053. if not self.session_interface.is_null_session(ctx.session):
  1054. self.session_interface.save_session(self, ctx.session, response)
  1055. return response
  1056. def do_teardown_request(
  1057. self,
  1058. exc: BaseException | None = _sentinel, # type: ignore[assignment]
  1059. ) -> None:
  1060. """Called after the request is dispatched and the response is
  1061. returned, right before the request context is popped.
  1062. This calls all functions decorated with
  1063. :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`
  1064. if a blueprint handled the request. Finally, the
  1065. :data:`request_tearing_down` signal is sent.
  1066. This is called by
  1067. :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,
  1068. which may be delayed during testing to maintain access to
  1069. resources.
  1070. :param exc: An unhandled exception raised while dispatching the
  1071. request. Detected from the current exception information if
  1072. not passed. Passed to each teardown function.
  1073. .. versionchanged:: 0.9
  1074. Added the ``exc`` argument.
  1075. """
  1076. if exc is _sentinel:
  1077. exc = sys.exc_info()[1]
  1078. for name in chain(request.blueprints, (None,)):
  1079. if name in self.teardown_request_funcs:
  1080. for func in reversed(self.teardown_request_funcs[name]):
  1081. self.ensure_sync(func)(exc)
  1082. request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)
  1083. def do_teardown_appcontext(
  1084. self,
  1085. exc: BaseException | None = _sentinel, # type: ignore[assignment]
  1086. ) -> None:
  1087. """Called right before the application context is popped.
  1088. When handling a request, the application context is popped
  1089. after the request context. See :meth:`do_teardown_request`.
  1090. This calls all functions decorated with
  1091. :meth:`teardown_appcontext`. Then the
  1092. :data:`appcontext_tearing_down` signal is sent.
  1093. This is called by
  1094. :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.
  1095. .. versionadded:: 0.9
  1096. """
  1097. if exc is _sentinel:
  1098. exc = sys.exc_info()[1]
  1099. for func in reversed(self.teardown_appcontext_funcs):
  1100. self.ensure_sync(func)(exc)
  1101. appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)
  1102. def app_context(self) -> AppContext:
  1103. """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``
  1104. block to push the context, which will make :data:`current_app`
  1105. point at this application.
  1106. An application context is automatically pushed by
  1107. :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`
  1108. when handling a request, and when running a CLI command. Use
  1109. this to manually create a context outside of these situations.
  1110. ::
  1111. with app.app_context():
  1112. init_db()
  1113. See :doc:`/appcontext`.
  1114. .. versionadded:: 0.9
  1115. """
  1116. return AppContext(self)
  1117. def request_context(self, environ: WSGIEnvironment) -> RequestContext:
  1118. """Create a :class:`~flask.ctx.RequestContext` representing a
  1119. WSGI environment. Use a ``with`` block to push the context,
  1120. which will make :data:`request` point at this request.
  1121. See :doc:`/reqcontext`.
  1122. Typically you should not call this from your own code. A request
  1123. context is automatically pushed by the :meth:`wsgi_app` when
  1124. handling a request. Use :meth:`test_request_context` to create
  1125. an environment and context instead of this method.
  1126. :param environ: a WSGI environment
  1127. """
  1128. return RequestContext(self, environ)
  1129. def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:
  1130. """Create a :class:`~flask.ctx.RequestContext` for a WSGI
  1131. environment created from the given values. This is mostly useful
  1132. during testing, where you may want to run a function that uses
  1133. request data without dispatching a full request.
  1134. See :doc:`/reqcontext`.
  1135. Use a ``with`` block to push the context, which will make
  1136. :data:`request` point at the request for the created
  1137. environment. ::
  1138. with app.test_request_context(...):
  1139. generate_report()
  1140. When using the shell, it may be easier to push and pop the
  1141. context manually to avoid indentation. ::
  1142. ctx = app.test_request_context(...)
  1143. ctx.push()
  1144. ...
  1145. ctx.pop()
  1146. Takes the same arguments as Werkzeug's
  1147. :class:`~werkzeug.test.EnvironBuilder`, with some defaults from
  1148. the application. See the linked Werkzeug docs for most of the
  1149. available arguments. Flask-specific behavior is listed here.
  1150. :param path: URL path being requested.
  1151. :param base_url: Base URL where the app is being served, which
  1152. ``path`` is relative to. If not given, built from
  1153. :data:`PREFERRED_URL_SCHEME`, ``subdomain``,
  1154. :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.
  1155. :param subdomain: Subdomain name to append to
  1156. :data:`SERVER_NAME`.
  1157. :param url_scheme: Scheme to use instead of
  1158. :data:`PREFERRED_URL_SCHEME`.
  1159. :param data: The request body, either as a string or a dict of
  1160. form keys and values.
  1161. :param json: If given, this is serialized as JSON and passed as
  1162. ``data``. Also defaults ``content_type`` to
  1163. ``application/json``.
  1164. :param args: other positional arguments passed to
  1165. :class:`~werkzeug.test.EnvironBuilder`.
  1166. :param kwargs: other keyword arguments passed to
  1167. :class:`~werkzeug.test.EnvironBuilder`.
  1168. """
  1169. from .testing import EnvironBuilder
  1170. builder = EnvironBuilder(self, *args, **kwargs)
  1171. try:
  1172. return self.request_context(builder.get_environ())
  1173. finally:
  1174. builder.close()
  1175. def wsgi_app(
  1176. self, environ: WSGIEnvironment, start_response: StartResponse
  1177. ) -> cabc.Iterable[bytes]:
  1178. """The actual WSGI application. This is not implemented in
  1179. :meth:`__call__` so that middlewares can be applied without
  1180. losing a reference to the app object. Instead of doing this::
  1181. app = MyMiddleware(app)
  1182. It's a better idea to do this instead::
  1183. app.wsgi_app = MyMiddleware(app.wsgi_app)
  1184. Then you still have the original application object around and
  1185. can continue to call methods on it.
  1186. .. versionchanged:: 0.7
  1187. Teardown events for the request and app contexts are called
  1188. even if an unhandled error occurs. Other events may not be
  1189. called depending on when an error occurs during dispatch.
  1190. See :ref:`callbacks-and-errors`.
  1191. :param environ: A WSGI environment.
  1192. :param start_response: A callable accepting a status code,
  1193. a list of headers, and an optional exception context to
  1194. start the response.
  1195. """
  1196. ctx = self.request_context(environ)
  1197. error: BaseException | None = None
  1198. try:
  1199. try:
  1200. ctx.push()
  1201. response = self.full_dispatch_request()
  1202. except Exception as e:
  1203. error = e
  1204. response = self.handle_exception(e)
  1205. except: # noqa: B001
  1206. error = sys.exc_info()[1]
  1207. raise
  1208. return response(environ, start_response)
  1209. finally:
  1210. if "werkzeug.debug.preserve_context" in environ:
  1211. environ["werkzeug.debug.preserve_context"](_cv_app.get())
  1212. environ["werkzeug.debug.preserve_context"](_cv_request.get())
  1213. if error is not None and self.should_ignore_error(error):
  1214. error = None
  1215. ctx.pop(error)
  1216. def __call__(
  1217. self, environ: WSGIEnvironment, start_response: StartResponse
  1218. ) -> cabc.Iterable[bytes]:
  1219. """The WSGI server calls the Flask application object as the
  1220. WSGI application. This calls :meth:`wsgi_app`, which can be
  1221. wrapped to apply middleware.
  1222. """
  1223. return self.wsgi_app(environ, start_response)