You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2089 lines
80KB

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