app.py 58 KB

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