app.py 60 KB

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