Split the App and Blueprint into Sansio and IO parts
Before adoption: this commit came in with the history the project adopted, so no landing records it.
This follows a similar structure in Werkzeug and allows for async based IO projects, specifically Quart, to base themselves on Flask. Note that the globals, and signals are specific to Flask and hence specific to Flask's IO. This means they cannot be moved to the sansio part of the codebase.
authored by pgjones · committed by pgjones · parent a64588f · Browse files · 10 files·+1621 added−1352 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+1621 added−1352 removed
- other:+1621 added−1352 removed
Provenance
- Commit
0ec7f71- Tree
86e03c0- Author
pgjones <philip.graham.jones@googlemail.com>- Committer
pgjones <philip.graham.jones@googlemail.com>- Parent
a64588f
10 files changed+1621 added−1352 removed
modified:src/flask/json/provider.py+2 added-2 removed
9 unmodified lines10 11 from werkzeug.http import http_date12 13 if t.TYPE_CHECKING: # pragma: no cover14- from ..app import Flask14+ from ..sansio.app import App15 from ..wrappers import Response16 17 18 class JSONProvider:14 unmodified lines33 34 .. versionadded:: 2.235 """36 37- def __init__(self, app: Flask) -> None:37+ def __init__(self, app: App) -> None:38 self._app = weakref.proxy(app)39 40 def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:41 """Serialize data as JSON.175 unmodified linesmodified:src/flask/sansio/app.py+29 added-1259 removed
2 unmodified lines3 import logging4 import os5 import sys6 import typing as t7-import weakref8-from collections.abc import Iterator as _abc_Iterator7 from datetime import timedelta10-from inspect import iscoroutinefunction8 from itertools import chain12-from types import TracebackType13-from urllib.parse import quote as _url_quote9 15-import click16-from werkzeug.datastructures import Headers17-from werkzeug.datastructures import ImmutableDict10 from werkzeug.exceptions import Aborter11 from werkzeug.exceptions import BadRequest12 from werkzeug.exceptions import BadRequestKeyError21-from werkzeug.exceptions import HTTPException22-from werkzeug.exceptions import InternalServerError13 from werkzeug.routing import BuildError14 from werkzeug.routing import Map25-from werkzeug.routing import MapAdapter26-from werkzeug.routing import RequestRedirect27-from werkzeug.routing import RoutingException15 from werkzeug.routing import Rule29-from werkzeug.serving import is_running_from_reloader16+from werkzeug.sansio.response import Response17 from werkzeug.utils import cached_property18 from werkzeug.utils import redirect as _wz_redirect32-from werkzeug.wrappers import Response as BaseResponse19 34-from . import cli35-from . import typing as ft36-from .config import Config37-from .config import ConfigAttribute38-from .ctx import _AppCtxGlobals39-from .ctx import AppContext40-from .ctx import RequestContext41-from .globals import _cv_app42-from .globals import _cv_request43-from .globals import g44-from .globals import request45-from .globals import request_ctx46-from .globals import session47-from .helpers import _split_blueprint_path48-from .helpers import get_debug_flag49-from .helpers import get_flashed_messages50-from .helpers import get_load_dotenv51-from .json.provider import DefaultJSONProvider52-from .json.provider import JSONProvider53-from .logging import create_logger20+from .. import typing as ft21+from ..config import Config22+from ..config import ConfigAttribute23+from ..ctx import _AppCtxGlobals24+from ..helpers import _split_blueprint_path25+from ..helpers import get_debug_flag26+from ..json.provider import DefaultJSONProvider27+from ..json.provider import JSONProvider28+from ..logging import create_logger29+from ..templating import DispatchingJinjaLoader30+from ..templating import Environment31 from .scaffold import _endpoint_from_view_func55-from .scaffold import _sentinel32 from .scaffold import find_package33 from .scaffold import Scaffold34 from .scaffold import setupmethod59-from .sessions import SecureCookieSessionInterface60-from .sessions import SessionInterface61-from .signals import appcontext_tearing_down62-from .signals import got_request_exception63-from .signals import request_finished64-from .signals import request_started65-from .signals import request_tearing_down66-from .templating import DispatchingJinjaLoader67-from .templating import Environment68-from .wrappers import Request69-from .wrappers import Response35 36 if t.TYPE_CHECKING: # pragma: no cover37+ from werkzeug.wrappers import Response as BaseResponse38 from .blueprints import Blueprint73- from .testing import FlaskClient74- from .testing import FlaskCliRunner39+ from ..testing import FlaskClient40+ from ..testing import FlaskCliRunner41 42 T_shell_context_processor = t.TypeVar(43 "T_shell_context_processor", bound=ft.ShellContextProcessorCallable44 )9 unmodified lines54 55 return timedelta(seconds=value)56 57 92-class Flask(Scaffold):58+class App(Scaffold):59 """The flask object implements a WSGI application and acts as the central60 object. It is passed the name of the module or package of the61 application. Once it is created it will act as a central registry for62 the view functions, the URL rules, template configuration and much more.88 unmodified lines151 This should only be set manually when it can't be detected152 automatically, such as for namespace packages.153 """154 189- #: The class that is used for request objects. See :class:`~flask.Request`190- #: for more information.191- request_class = Request192-193- #: The class that is used for response objects. See194- #: :class:`~flask.Response` for more information.195- response_class = Response196-155 #: The class of the object assigned to :attr:`aborter`, created by156 #: :meth:`create_aborter`. That object is called by157 #: :func:`flask.abort` to raise HTTP errors, and can be158 #: called directly as well.88 unmodified lines247 #: easier configuration.248 #:249 jinja_options: dict = {}250 293- #: Default configuration parameters.294- default_config = ImmutableDict(295- {296- "DEBUG": None,297- "TESTING": False,298- "PROPAGATE_EXCEPTIONS": None,299- "SECRET_KEY": None,300- "PERMANENT_SESSION_LIFETIME": timedelta(days=31),301- "USE_X_SENDFILE": False,302- "SERVER_NAME": None,303- "APPLICATION_ROOT": "/",304- "SESSION_COOKIE_NAME": "session",305- "SESSION_COOKIE_DOMAIN": None,306- "SESSION_COOKIE_PATH": None,307- "SESSION_COOKIE_HTTPONLY": True,308- "SESSION_COOKIE_SECURE": False,309- "SESSION_COOKIE_SAMESITE": None,310- "SESSION_REFRESH_EACH_REQUEST": True,311- "MAX_CONTENT_LENGTH": None,312- "SEND_FILE_MAX_AGE_DEFAULT": None,313- "TRAP_BAD_REQUEST_ERRORS": None,314- "TRAP_HTTP_EXCEPTIONS": False,315- "EXPLAIN_TEMPLATE_LOADING": False,316- "PREFERRED_URL_SCHEME": "http",317- "TEMPLATES_AUTO_RELOAD": None,318- "MAX_COOKIE_SIZE": 4093,319- }320- )321-251 #: The rule object to use for URL rules created. This is used by252 #: :meth:`add_url_rule`. Defaults to :class:`werkzeug.routing.Rule`.253 #:254 #: .. versionadded:: 0.718 unmodified lines273 #:274 #: .. versionadded:: 1.0275 test_cli_runner_class: type[FlaskCliRunner] | None = None276 348- #: the session interface to use. By default an instance of349- #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.350- #:351- #: .. versionadded:: 0.8352- session_interface: SessionInterface = SecureCookieSessionInterface()277+ default_config: dict278+ response_class: type[Response]279 280 def __init__(281 self,282 import_name: str,116 unmodified lines399 #: for value in values)400 #:401 #: app = Flask(__name__)402 #: app.url_map.converters['list'] = ListConverter477- self.url_map = self.url_map_class()403+ self.url_map = self.url_map_class(host_matching=host_matching)404 479- self.url_map.host_matching = host_matching405 self.subdomain_matching = subdomain_matching406 407 # tracks internally if the application already handled at least one408 # request.409 self._got_first_request = False410 486- # Add a static route using the provided static_url_path, static_host,487- # and static_folder if there is a configured static_folder.488- # Note we do this without checking if static_folder exists.489- # For one, it might be created while the server is running (e.g. during490- # development). Also, Google App Engine stores static files somewhere491- if self.has_static_folder:492- assert (493- bool(static_host) == host_matching494- ), "Invalid static_host/host_matching combination"495- # Use a weakref to avoid creating a reference cycle between the app496- # and the view function (see #3761).497- self_ref = weakref.ref(self)498- self.add_url_rule(499- f"{self.static_url_path}/<path:filename>",500- endpoint="static",501- host=static_host,502- view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950503- )504-411 # Set the name of the Click group in case someone wants to add412 # the app's commands to another CLI tool.413 self.cli.name = self.name414 62 unmodified lines477 effect.478 """479 return self.create_jinja_environment()480 481+ def create_jinja_environment(self) -> Environment:482+ raise NotImplementedError()483+484 def make_config(self, instance_relative: bool = False) -> Config:485 """Used to create the config attribute by the Flask constructor.486 The `instance_relative` parameter is passed in from the constructor487 of Flask (there named `instance_relative_config`) and indicates if33 unmodified lines521 if prefix is None:522 return os.path.join(package_path, "instance")523 return os.path.join(prefix, "var", f"{self.name}-instance")524 616- def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:617- """Opens a resource from the application's instance folder618- (:attr:`instance_path`). Otherwise works like619- :meth:`open_resource`. Instance resources can also be opened for620- writing.621-622- :param resource: the name of the resource. To access resources within623- subfolders use forward slashes as separator.624- :param mode: resource file opening mode, default is 'rb'.625- """626- return open(os.path.join(self.instance_path, resource), mode)627-628- def create_jinja_environment(self) -> Environment:629- """Create the Jinja environment based on :attr:`jinja_options`630- and the various Jinja-related methods of the app. Changing631- :attr:`jinja_options` after this will have no effect. Also adds632- Flask-related globals and filters to the environment.633-634- .. versionchanged:: 0.11635- ``Environment.auto_reload`` set in accordance with636- ``TEMPLATES_AUTO_RELOAD`` configuration option.637-638- .. versionadded:: 0.5639- """640- options = dict(self.jinja_options)641-642- if "autoescape" not in options:643- options["autoescape"] = self.select_jinja_autoescape644-645- if "auto_reload" not in options:646- auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]647-648- if auto_reload is None:649- auto_reload = self.debug650-651- options["auto_reload"] = auto_reload652-653- rv = self.jinja_environment(self, **options)654- rv.globals.update(655- url_for=self.url_for,656- get_flashed_messages=get_flashed_messages,657- config=self.config,658- # request, session and g are normally added with the659- # context processor for efficiency reasons but for imported660- # templates we also want the proxies in there.661- request=request,662- session=session,663- g=g,664- )665- rv.policies["json.dumps_function"] = self.json.dumps666- return rv667-525 def create_global_jinja_loader(self) -> DispatchingJinjaLoader:526 """Creates the loader for the Jinja2 environment. Can be used to527 override just the loader and keeping the rest unchanged. It's528 discouraged to override this function. Instead one should override18 unmodified lines547 if filename is None:548 return True549 return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))550 694- def update_template_context(self, context: dict) -> None:695- """Update the template context with some commonly used variables.696- This injects request, session, config and g into the template697- context as well as everything template context processors want698- to inject. Note that the as of Flask 0.6, the original values699- in the context will not be overridden if a context processor700- decides to return a value with the same key.701-702- :param context: the context as a dictionary that is updated in place703- to add extra variables.704- """705- names: t.Iterable[str | None] = (None,)706-707- # A template may be rendered outside a request context.708- if request:709- names = chain(names, reversed(request.blueprints))710-711- # The values passed to render_template take precedence. Keep a712- # copy to re-apply after all context functions.713- orig_ctx = context.copy()714-715- for name in names:716- if name in self.template_context_processors:717- for func in self.template_context_processors[name]:718- context.update(func())719-720- context.update(orig_ctx)721-722- def make_shell_context(self) -> dict:723- """Returns the shell context for an interactive shell for this724- application. This runs all the registered shell context725- processors.726-727- .. versionadded:: 0.11728- """729- rv = {"app": self, "g": g}730- for processor in self.shell_context_processors:731- rv.update(processor())732- return rv733-551 @property552 def debug(self) -> bool:553 """Whether debug mode is enabled. When using ``flask run`` to start the554 development server, an interactive debugger will be shown for unhandled12 unmodified lines567 568 if self.config["TEMPLATES_AUTO_RELOAD"] is None:569 self.jinja_env.auto_reload = value570 754- def run(755- self,756- host: str | None = None,757- port: int | None = None,758- debug: bool | None = None,759- load_dotenv: bool = True,760- **options: t.Any,761- ) -> None:762- """Runs the application on a local development server.763-764- Do not use ``run()`` in a production setting. It is not intended to765- meet security and performance requirements for a production server.766- Instead, see :doc:`/deploying/index` for WSGI server recommendations.767-768- If the :attr:`debug` flag is set the server will automatically reload769- for code changes and show a debugger in case an exception happened.770-771- If you want to run the application in debug mode, but disable the772- code execution on the interactive debugger, you can pass773- ``use_evalex=False`` as parameter. This will keep the debugger's774- traceback screen active, but disable code execution.775-776- It is not recommended to use this function for development with777- automatic reloading as this is badly supported. Instead you should778- be using the :command:`flask` command line script's ``run`` support.779-780- .. admonition:: Keep in Mind781-782- Flask will suppress any server error with a generic error page783- unless it is in debug mode. As such to enable just the784- interactive debugger without the code reloading, you have to785- invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.786- Setting ``use_debugger`` to ``True`` without being in debug mode787- won't catch any exceptions because there won't be any to788- catch.789-790- :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to791- have the server available externally as well. Defaults to792- ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable793- if present.794- :param port: the port of the webserver. Defaults to ``5000`` or the795- port defined in the ``SERVER_NAME`` config variable if present.796- :param debug: if given, enable or disable debug mode. See797- :attr:`debug`.798- :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`799- files to set environment variables. Will also change the working800- directory to the directory containing the first file found.801- :param options: the options to be forwarded to the underlying Werkzeug802- server. See :func:`werkzeug.serving.run_simple` for more803- information.804-805- .. versionchanged:: 1.0806- If installed, python-dotenv will be used to load environment807- variables from :file:`.env` and :file:`.flaskenv` files.808-809- The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.810-811- Threaded mode is enabled by default.812-813- .. versionchanged:: 0.10814- The default port is now picked from the ``SERVER_NAME``815- variable.816- """817- # Ignore this call so that it doesn't start another server if818- # the 'flask run' command is used.819- if os.environ.get("FLASK_RUN_FROM_CLI") == "true":820- if not is_running_from_reloader():821- click.secho(822- " * Ignoring a call to 'app.run()' that would block"823- " the current 'flask' CLI command.\n"824- " Only call 'app.run()' in an 'if __name__ =="825- ' "__main__"\' guard.',826- fg="red",827- )828-829- return830-831- if get_load_dotenv(load_dotenv):832- cli.load_dotenv()833-834- # if set, env var overrides existing value835- if "FLASK_DEBUG" in os.environ:836- self.debug = get_debug_flag()837-838- # debug passed to method overrides all other sources839- if debug is not None:840- self.debug = bool(debug)841-842- server_name = self.config.get("SERVER_NAME")843- sn_host = sn_port = None844-845- if server_name:846- sn_host, _, sn_port = server_name.partition(":")847-848- if not host:849- if sn_host:850- host = sn_host851- else:852- host = "127.0.0.1"853-854- if port or port == 0:855- port = int(port)856- elif sn_port:857- port = int(sn_port)858- else:859- port = 5000860-861- options.setdefault("use_reloader", self.debug)862- options.setdefault("use_debugger", self.debug)863- options.setdefault("threaded", True)864-865- cli.show_server_banner(self.debug, self.name)866-867- from werkzeug.serving import run_simple868-869- try:870- run_simple(t.cast(str, host), port, self, **options)871- finally:872- # reset the first request information if the development server873- # reset normally. This makes it possible to restart the server874- # without reloader and that stuff from an interactive shell.875- self._got_first_request = False876-877- def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:878- """Creates a test client for this application. For information879- about unit testing head over to :doc:`/testing`.880-881- Note that if you are testing for assertions or exceptions in your882- application code, you must set ``app.testing = True`` in order for the883- exceptions to propagate to the test client. Otherwise, the exception884- will be handled by the application (not visible to the test client) and885- the only indication of an AssertionError or other exception will be a886- 500 status code response to the test client. See the :attr:`testing`887- attribute. For example::888-889- app.testing = True890- client = app.test_client()891-892- The test client can be used in a ``with`` block to defer the closing down893- of the context until the end of the ``with`` block. This is useful if894- you want to access the context locals for testing::895-896- with app.test_client() as c:897- rv = c.get('/?vodka=42')898- assert request.args['vodka'] == '42'899-900- Additionally, you may pass optional keyword arguments that will then901- be passed to the application's :attr:`test_client_class` constructor.902- For example::903-904- from flask.testing import FlaskClient905-906- class CustomClient(FlaskClient):907- def __init__(self, *args, **kwargs):908- self._authentication = kwargs.pop("authentication")909- super(CustomClient,self).__init__( *args, **kwargs)910-911- app.test_client_class = CustomClient912- client = app.test_client(authentication='Basic ....')913-914- See :class:`~flask.testing.FlaskClient` for more information.915-916- .. versionchanged:: 0.4917- added support for ``with`` block usage for the client.918-919- .. versionadded:: 0.7920- The `use_cookies` parameter was added as well as the ability921- to override the client to be used by setting the922- :attr:`test_client_class` attribute.923-924- .. versionchanged:: 0.11925- Added `**kwargs` to support passing additional keyword arguments to926- the constructor of :attr:`test_client_class`.927- """928- cls = self.test_client_class929- if cls is None:930- from .testing import FlaskClient as cls931- return cls( # type: ignore932- self, self.response_class, use_cookies=use_cookies, **kwargs933- )934-935- def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:936- """Create a CLI runner for testing CLI commands.937- See :ref:`testing-cli`.938-939- Returns an instance of :attr:`test_cli_runner_class`, by default940- :class:`~flask.testing.FlaskCliRunner`. The Flask app object is941- passed as the first argument.942-943- .. versionadded:: 1.0944- """945- cls = self.test_cli_runner_class946-947- if cls is None:948- from .testing import FlaskCliRunner as cls949-950- return cls(self, **kwargs) # type: ignore951-571 @setupmethod572 def register_blueprint(self, blueprint: Blueprint, **options: t.Any) -> None:573 """Register a :class:`~flask.Blueprint` on the application. Keyword574 arguments passed to this method will override the defaults set on the246 unmodified lines821 """822 self.shell_context_processors.append(f)823 return f824 1206- def _find_error_handler(self, e: Exception) -> ft.ErrorHandlerCallable | None:825+ def _find_error_handler(826+ self, e: Exception, blueprints: list[str]827+ ) -> ft.ErrorHandlerCallable | None:828 """Return a registered error handler for an exception in this order:829 blueprint handler for a specific code, app handler for a specific code,830 blueprint handler for an exception class, app handler for an exception831 class, or ``None`` if a suitable handler is not found.832 """833 exc_class, code = self._get_exc_class_and_code(type(e))1213- names = (*request.blueprints, None)834+ names = (*blueprints, None)835 836 for c in (code, None) if code is not None else (None,):837 for name in names:838 handler_map = self.error_handler_spec[name][c]7 unmodified lines846 if handler is not None:847 return handler848 return None849 1229- def handle_http_exception(1230- self, e: HTTPException1231- ) -> HTTPException | ft.ResponseReturnValue:1232- """Handles an HTTP exception. By default this will invoke the1233- registered error handlers and fall back to returning the1234- exception as response.1235-1236- .. versionchanged:: 1.0.31237- ``RoutingException``, used internally for actions such as1238- slash redirects during routing, is not passed to error1239- handlers.1240-1241- .. versionchanged:: 1.01242- Exceptions are looked up by code *and* by MRO, so1243- ``HTTPException`` subclasses can be handled with a catch-all1244- handler for the base ``HTTPException``.1245-1246- .. versionadded:: 0.31247- """1248- # Proxy exceptions don't have error codes. We want to always return1249- # those unchanged as errors1250- if e.code is None:1251- return e1252-1253- # RoutingExceptions are used internally to trigger routing1254- # actions, such as slash redirects raising RequestRedirect. They1255- # are not raised or handled in user code.1256- if isinstance(e, RoutingException):1257- return e1258-1259- handler = self._find_error_handler(e)1260- if handler is None:1261- return e1262- return self.ensure_sync(handler)(e)1263-850 def trap_http_exception(self, e: Exception) -> bool:851 """Checks if an HTTP exception should be trapped or not. By default852 this will return ``False`` for all exceptions except for a bad request853 key error if ``TRAP_BAD_REQUEST_ERRORS`` is set to ``True``. It27 unmodified lines881 return isinstance(e, BadRequest)882 883 return False884 1299- def handle_user_exception(1300- self, e: Exception1301- ) -> HTTPException | ft.ResponseReturnValue:1302- """This method is called whenever an exception occurs that1303- should be handled. A special case is :class:`~werkzeug1304- .exceptions.HTTPException` which is forwarded to the1305- :meth:`handle_http_exception` method. This function will either1306- return a response value or reraise the exception with the same1307- traceback.1308-1309- .. versionchanged:: 1.01310- Key errors raised from request data like ``form`` show the1311- bad key in debug mode rather than a generic bad request1312- message.1313-1314- .. versionadded:: 0.71315- """1316- if isinstance(e, BadRequestKeyError) and (1317- self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]1318- ):1319- e.show_exception = True1320-1321- if isinstance(e, HTTPException) and not self.trap_http_exception(e):1322- return self.handle_http_exception(e)1323-1324- handler = self._find_error_handler(e)1325-1326- if handler is None:1327- raise1328-1329- return self.ensure_sync(handler)(e)1330-1331- def handle_exception(self, e: Exception) -> Response:1332- """Handle an exception that did not have an error handler1333- associated with it, or that was raised from an error handler.1334- This always causes a 500 ``InternalServerError``.1335-1336- Always sends the :data:`got_request_exception` signal.1337-1338- If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug1339- mode, the error will be re-raised so that the debugger can1340- display it. Otherwise, the original exception is logged, and1341- an :exc:`~werkzeug.exceptions.InternalServerError` is returned.1342-1343- If an error handler is registered for ``InternalServerError`` or1344- ``500``, it will be used. For consistency, the handler will1345- always receive the ``InternalServerError``. The original1346- unhandled exception is available as ``e.original_exception``.1347-1348- .. versionchanged:: 1.1.01349- Always passes the ``InternalServerError`` instance to the1350- handler, setting ``original_exception`` to the unhandled1351- error.1352-1353- .. versionchanged:: 1.1.01354- ``after_request`` functions and other finalization is done1355- even for the default 500 response when there is no handler.1356-1357- .. versionadded:: 0.31358- """1359- exc_info = sys.exc_info()1360- got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)1361- propagate = self.config["PROPAGATE_EXCEPTIONS"]1362-1363- if propagate is None:1364- propagate = self.testing or self.debug1365-1366- if propagate:1367- # Re-raise if called with an active exception, otherwise1368- # raise the passed in exception.1369- if exc_info[1] is e:1370- raise1371-1372- raise e1373-1374- self.log_exception(exc_info)1375- server_error: InternalServerError | ft.ResponseReturnValue1376- server_error = InternalServerError(original_exception=e)1377- handler = self._find_error_handler(server_error)1378-1379- if handler is not None:1380- server_error = self.ensure_sync(handler)(server_error)1381-1382- return self.finalize_request(server_error, from_error_handler=True)1383-1384- def log_exception(1385- self,1386- exc_info: (tuple[type, BaseException, TracebackType] | tuple[None, None, None]),1387- ) -> None:1388- """Logs an exception. This is called by :meth:`handle_exception`1389- if debugging is disabled and right before the handler is called.1390- The default implementation logs the exception as error on the1391- :attr:`logger`.1392-1393- .. versionadded:: 0.81394- """1395- self.logger.error(1396- f"Exception on {request.path} [{request.method}]", exc_info=exc_info1397- )1398-1399- def raise_routing_exception(self, request: Request) -> t.NoReturn:1400- """Intercept routing exceptions and possibly do something else.1401-1402- In debug mode, intercept a routing redirect and replace it with1403- an error if the body will be discarded.1404-1405- With modern Werkzeug this shouldn't occur, since it now uses a1406- 308 status which tells the browser to resend the method and1407- body.1408-1409- .. versionchanged:: 2.11410- Don't intercept 307 and 308 redirects.1411-1412- :meta private:1413- :internal:1414- """1415- if (1416- not self.debug1417- or not isinstance(request.routing_exception, RequestRedirect)1418- or request.routing_exception.code in {307, 308}1419- or request.method in {"GET", "HEAD", "OPTIONS"}1420- ):1421- raise request.routing_exception # type: ignore1422-1423- from .debughelpers import FormDataRoutingRedirect1424-1425- raise FormDataRoutingRedirect(request)1426-1427- def dispatch_request(self) -> ft.ResponseReturnValue:1428- """Does the request dispatching. Matches the URL and returns the1429- return value of the view or error handler. This does not have to1430- be a response object. In order to convert the return value to a1431- proper response object, call :func:`make_response`.1432-1433- .. versionchanged:: 0.71434- This no longer does the exception handling, this code was1435- moved to the new :meth:`full_dispatch_request`.1436- """1437- req = request_ctx.request1438- if req.routing_exception is not None:1439- self.raise_routing_exception(req)1440- rule: Rule = req.url_rule # type: ignore[assignment]1441- # if we provide automatic options for this URL and the1442- # request came with the OPTIONS method, reply automatically1443- if (1444- getattr(rule, "provide_automatic_options", False)1445- and req.method == "OPTIONS"1446- ):1447- return self.make_default_options_response()1448- # otherwise dispatch to the handler for that endpoint1449- view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]1450- return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)1451-1452- def full_dispatch_request(self) -> Response:1453- """Dispatches the request and on top of that performs request1454- pre and postprocessing as well as HTTP exception catching and1455- error handling.1456-1457- .. versionadded:: 0.71458- """1459- self._got_first_request = True1460-1461- try:1462- request_started.send(self, _async_wrapper=self.ensure_sync)1463- rv = self.preprocess_request()1464- if rv is None:1465- rv = self.dispatch_request()1466- except Exception as e:1467- rv = self.handle_user_exception(e)1468- return self.finalize_request(rv)1469-1470- def finalize_request(1471- self,1472- rv: ft.ResponseReturnValue | HTTPException,1473- from_error_handler: bool = False,1474- ) -> Response:1475- """Given the return value from a view function this finalizes1476- the request by converting it into a response and invoking the1477- postprocessing functions. This is invoked for both normal1478- request dispatching as well as error handlers.1479-1480- Because this means that it might be called as a result of a1481- failure a special safe mode is available which can be enabled1482- with the `from_error_handler` flag. If enabled, failures in1483- response processing will be logged and otherwise ignored.1484-1485- :internal:1486- """1487- response = self.make_response(rv)1488- try:1489- response = self.process_response(response)1490- request_finished.send(1491- self, _async_wrapper=self.ensure_sync, response=response1492- )1493- except Exception:1494- if not from_error_handler:1495- raise1496- self.logger.exception(1497- "Request finalizing failed with an error while handling an error"1498- )1499- return response1500-1501- def make_default_options_response(self) -> Response:1502- """This method is called to create the default ``OPTIONS`` response.1503- This can be changed through subclassing to change the default1504- behavior of ``OPTIONS`` responses.1505-1506- .. versionadded:: 0.71507- """1508- adapter = request_ctx.url_adapter1509- methods = adapter.allowed_methods() # type: ignore[union-attr]1510- rv = self.response_class()1511- rv.allow.update(methods)1512- return rv1513-885 def should_ignore_error(self, error: BaseException | None) -> bool:886 """This is called to figure out if an error should be ignored887 or not as far as the teardown system is concerned. If this888 function returns ``True`` then the teardown handlers will not be2 unmodified lines891 .. versionadded:: 0.10892 """893 return False894 1524- def ensure_sync(self, func: t.Callable) -> t.Callable:1525- """Ensure that the function is synchronous for WSGI workers.1526- Plain ``def`` functions are returned as-is. ``async def``1527- functions are wrapped to run and wait for the response.1528-1529- Override this method to change how the app runs async views.1530-1531- .. versionadded:: 2.01532- """1533- if iscoroutinefunction(func):1534- return self.async_to_sync(func)1535-1536- return func1537-1538- def async_to_sync(1539- self, func: t.Callable[..., t.Coroutine]1540- ) -> t.Callable[..., t.Any]:1541- """Return a sync function that will run the coroutine function.1542-1543- .. code-block:: python1544-1545- result = app.async_to_sync(func)(*args, **kwargs)1546-1547- Override this method to change how the app converts async code1548- to be synchronously callable.1549-1550- .. versionadded:: 2.01551- """1552- try:1553- from asgiref.sync import async_to_sync as asgiref_async_to_sync1554- except ImportError:1555- raise RuntimeError(1556- "Install Flask with the 'async' extra in order to use async views."1557- ) from None1558-1559- return asgiref_async_to_sync(func)1560-1561- def url_for(1562- self,1563- endpoint: str,1564- *,1565- _anchor: str | None = None,1566- _method: str | None = None,1567- _scheme: str | None = None,1568- _external: bool | None = None,1569- **values: t.Any,1570- ) -> str:1571- """Generate a URL to the given endpoint with the given values.1572-1573- This is called by :func:`flask.url_for`, and can be called1574- directly as well.1575-1576- An *endpoint* is the name of a URL rule, usually added with1577- :meth:`@app.route() <route>`, and usually the same name as the1578- view function. A route defined in a :class:`~flask.Blueprint`1579- will prepend the blueprint's name separated by a ``.`` to the1580- endpoint.1581-1582- In some cases, such as email messages, you want URLs to include1583- the scheme and domain, like ``https://example.com/hello``. When1584- not in an active request, URLs will be external by default, but1585- this requires setting :data:`SERVER_NAME` so Flask knows what1586- domain to use. :data:`APPLICATION_ROOT` and1587- :data:`PREFERRED_URL_SCHEME` should also be configured as1588- needed. This config is only used when not in an active request.1589-1590- Functions can be decorated with :meth:`url_defaults` to modify1591- keyword arguments before the URL is built.1592-1593- If building fails for some reason, such as an unknown endpoint1594- or incorrect values, the app's :meth:`handle_url_build_error`1595- method is called. If that returns a string, that is returned,1596- otherwise a :exc:`~werkzeug.routing.BuildError` is raised.1597-1598- :param endpoint: The endpoint name associated with the URL to1599- generate. If this starts with a ``.``, the current blueprint1600- name (if any) will be used.1601- :param _anchor: If given, append this as ``#anchor`` to the URL.1602- :param _method: If given, generate the URL associated with this1603- method for the endpoint.1604- :param _scheme: If given, the URL will have this scheme if it1605- is external.1606- :param _external: If given, prefer the URL to be internal1607- (False) or require it to be external (True). External URLs1608- include the scheme and domain. When not in an active1609- request, URLs are external by default.1610- :param values: Values to use for the variable parts of the URL1611- rule. Unknown keys are appended as query string arguments,1612- like ``?a=b&c=d``.1613-1614- .. versionadded:: 2.21615- Moved from ``flask.url_for``, which calls this method.1616- """1617- req_ctx = _cv_request.get(None)1618-1619- if req_ctx is not None:1620- url_adapter = req_ctx.url_adapter1621- blueprint_name = req_ctx.request.blueprint1622-1623- # If the endpoint starts with "." and the request matches a1624- # blueprint, the endpoint is relative to the blueprint.1625- if endpoint[:1] == ".":1626- if blueprint_name is not None:1627- endpoint = f"{blueprint_name}{endpoint}"1628- else:1629- endpoint = endpoint[1:]1630-1631- # When in a request, generate a URL without scheme and1632- # domain by default, unless a scheme is given.1633- if _external is None:1634- _external = _scheme is not None1635- else:1636- app_ctx = _cv_app.get(None)1637-1638- # If called by helpers.url_for, an app context is active,1639- # use its url_adapter. Otherwise, app.url_for was called1640- # directly, build an adapter.1641- if app_ctx is not None:1642- url_adapter = app_ctx.url_adapter1643- else:1644- url_adapter = self.create_url_adapter(None)1645-1646- if url_adapter is None:1647- raise RuntimeError(1648- "Unable to build URLs outside an active request"1649- " without 'SERVER_NAME' configured. Also configure"1650- " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as"1651- " needed."1652- )1653-1654- # When outside a request, generate a URL with scheme and1655- # domain by default.1656- if _external is None:1657- _external = True1658-1659- # It is an error to set _scheme when _external=False, in order1660- # to avoid accidental insecure URLs.1661- if _scheme is not None and not _external:1662- raise ValueError("When specifying '_scheme', '_external' must be True.")1663-1664- self.inject_url_defaults(endpoint, values)1665-1666- try:1667- rv = url_adapter.build( # type: ignore[union-attr]1668- endpoint,1669- values,1670- method=_method,1671- url_scheme=_scheme,1672- force_external=_external,1673- )1674- except BuildError as error:1675- values.update(1676- _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external1677- )1678- return self.handle_url_build_error(error, endpoint, values)1679-1680- if _anchor is not None:1681- _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")1682- rv = f"{rv}#{_anchor}"1683-1684- return rv1685-895 def redirect(self, location: str, code: int = 302) -> BaseResponse:896 """Create a redirect response object.897 898 This is called by :func:`flask.redirect`, and can be called4 unmodified lines903 904 .. versionadded:: 2.2905 Moved from ``flask.redirect``, which calls this method.906 """1698- return _wz_redirect(location, code=code, Response=self.response_class)907+ return _wz_redirect(908+ location, code=code, Response=self.response_class # type: ignore[arg-type]909+ )910 1700- def make_response(self, rv: ft.ResponseReturnValue) -> Response:1701- """Convert the return value from a view function to an instance of1702- :attr:`response_class`.1703-1704- :param rv: the return value from the view function. The view function1705- must return a response. Returning ``None``, or the view ending1706- without returning, is not allowed. The following types are allowed1707- for ``view_rv``:1708-1709- ``str``1710- A response object is created with the string encoded to UTF-81711- as the body.1712-1713- ``bytes``1714- A response object is created with the bytes as the body.1715-1716- ``dict``1717- A dictionary that will be jsonify'd before being returned.1718-1719- ``list``1720- A list that will be jsonify'd before being returned.1721-1722- ``generator`` or ``iterator``1723- A generator that returns ``str`` or ``bytes`` to be1724- streamed as the response.1725-1726- ``tuple``1727- Either ``(body, status, headers)``, ``(body, status)``, or1728- ``(body, headers)``, where ``body`` is any of the other types1729- allowed here, ``status`` is a string or an integer, and1730- ``headers`` is a dictionary or a list of ``(key, value)``1731- tuples. If ``body`` is a :attr:`response_class` instance,1732- ``status`` overwrites the exiting value and ``headers`` are1733- extended.1734-1735- :attr:`response_class`1736- The object is returned unchanged.1737-1738- other :class:`~werkzeug.wrappers.Response` class1739- The object is coerced to :attr:`response_class`.1740-1741- :func:`callable`1742- The function is called as a WSGI application. The result is1743- used to create a response object.1744-1745- .. versionchanged:: 2.21746- A generator will be converted to a streaming response.1747- A list will be converted to a JSON response.1748-1749- .. versionchanged:: 1.11750- A dict will be converted to a JSON response.1751-1752- .. versionchanged:: 0.91753- Previously a tuple was interpreted as the arguments for the1754- response object.1755- """1756-1757- status = headers = None1758-1759- # unpack tuple returns1760- if isinstance(rv, tuple):1761- len_rv = len(rv)1762-1763- # a 3-tuple is unpacked directly1764- if len_rv == 3:1765- rv, status, headers = rv # type: ignore[misc]1766- # decide if a 2-tuple has status or headers1767- elif len_rv == 2:1768- if isinstance(rv[1], (Headers, dict, tuple, list)):1769- rv, headers = rv1770- else:1771- rv, status = rv # type: ignore[assignment,misc]1772- # other sized tuples are not allowed1773- else:1774- raise TypeError(1775- "The view function did not return a valid response tuple."1776- " The tuple must have the form (body, status, headers),"1777- " (body, status), or (body, headers)."1778- )1779-1780- # the body must not be None1781- if rv is None:1782- raise TypeError(1783- f"The view function for {request.endpoint!r} did not"1784- " return a valid response. The function either returned"1785- " None or ended without a return statement."1786- )1787-1788- # make sure the body is an instance of the response class1789- if not isinstance(rv, self.response_class):1790- if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, _abc_Iterator):1791- # let the response class set the status and headers instead of1792- # waiting to do it manually, so that the class can handle any1793- # special logic1794- rv = self.response_class(1795- rv,1796- status=status,1797- headers=headers, # type: ignore[arg-type]1798- )1799- status = headers = None1800- elif isinstance(rv, (dict, list)):1801- rv = self.json.response(rv)1802- elif isinstance(rv, BaseResponse) or callable(rv):1803- # evaluate a WSGI callable, or coerce a different response1804- # class to the correct type1805- try:1806- rv = self.response_class.force_type(1807- rv, request.environ # type: ignore[arg-type]1808- )1809- except TypeError as e:1810- raise TypeError(1811- f"{e}\nThe view function did not return a valid"1812- " response. The return type must be a string,"1813- " dict, list, tuple with headers or status,"1814- " Response instance, or WSGI callable, but it"1815- f" was a {type(rv).__name__}."1816- ).with_traceback(sys.exc_info()[2]) from None1817- else:1818- raise TypeError(1819- "The view function did not return a valid"1820- " response. The return type must be a string,"1821- " dict, list, tuple with headers or status,"1822- " Response instance, or WSGI callable, but it was a"1823- f" {type(rv).__name__}."1824- )1825-1826- rv = t.cast(Response, rv)1827- # prefer the status if it was provided1828- if status is not None:1829- if isinstance(status, (str, bytes, bytearray)):1830- rv.status = status1831- else:1832- rv.status_code = status1833-1834- # extend existing headers with provided headers1835- if headers:1836- rv.headers.update(headers) # type: ignore[arg-type]1837-1838- return rv1839-1840- def create_url_adapter(self, request: Request | None) -> MapAdapter | None:1841- """Creates a URL adapter for the given request. The URL adapter1842- is created at a point where the request context is not yet set1843- up so the request is passed explicitly.1844-1845- .. versionadded:: 0.61846-1847- .. versionchanged:: 0.91848- This can now also be called without a request object when the1849- URL adapter is created for the application context.1850-1851- .. versionchanged:: 1.01852- :data:`SERVER_NAME` no longer implicitly enables subdomain1853- matching. Use :attr:`subdomain_matching` instead.1854- """1855- if request is not None:1856- # If subdomain matching is disabled (the default), use the1857- # default subdomain in all cases. This should be the default1858- # in Werkzeug but it currently does not have that feature.1859- if not self.subdomain_matching:1860- subdomain = self.url_map.default_subdomain or None1861- else:1862- subdomain = None1863-1864- return self.url_map.bind_to_environ(1865- request.environ,1866- server_name=self.config["SERVER_NAME"],1867- subdomain=subdomain,1868- )1869- # We need at the very least the server name to be set for this1870- # to work.1871- if self.config["SERVER_NAME"] is not None:1872- return self.url_map.bind(1873- self.config["SERVER_NAME"],1874- script_name=self.config["APPLICATION_ROOT"],1875- url_scheme=self.config["PREFERRED_URL_SCHEME"],1876- )1877-1878- return None1879-911 def inject_url_defaults(self, endpoint: str, values: dict) -> None:912 """Injects the URL defaults for the given endpoint directly into913 the values dictionary passed. This is used internally and914 automatically called on URL building.46 unmodified lines961 if error is sys.exc_info()[1]:962 raise963 964 raise error1934-1935- def preprocess_request(self) -> ft.ResponseReturnValue | None:1936- """Called before the request is dispatched. Calls1937- :attr:`url_value_preprocessors` registered with the app and the1938- current blueprint (if any). Then calls :attr:`before_request_funcs`1939- registered with the app and the blueprint.1940-1941- If any :meth:`before_request` handler returns a non-None value, the1942- value is handled as if it was the return value from the view, and1943- further request handling is stopped.1944- """1945- names = (None, *reversed(request.blueprints))1946-1947- for name in names:1948- if name in self.url_value_preprocessors:1949- for url_func in self.url_value_preprocessors[name]:1950- url_func(request.endpoint, request.view_args)1951-1952- for name in names:1953- if name in self.before_request_funcs:1954- for before_func in self.before_request_funcs[name]:1955- rv = self.ensure_sync(before_func)()1956-1957- if rv is not None:1958- return rv1959-1960- return None1961-1962- def process_response(self, response: Response) -> Response:1963- """Can be overridden in order to modify the response object1964- before it's sent to the WSGI server. By default this will1965- call all the :meth:`after_request` decorated functions.1966-1967- .. versionchanged:: 0.51968- As of Flask 0.5 the functions registered for after request1969- execution are called in reverse order of registration.1970-1971- :param response: a :attr:`response_class` object.1972- :return: a new response object or the same, has to be an1973- instance of :attr:`response_class`.1974- """1975- ctx = request_ctx._get_current_object() # type: ignore[attr-defined]1976-1977- for func in ctx._after_request_functions:1978- response = self.ensure_sync(func)(response)1979-1980- for name in chain(request.blueprints, (None,)):1981- if name in self.after_request_funcs:1982- for func in reversed(self.after_request_funcs[name]):1983- response = self.ensure_sync(func)(response)1984-1985- if not self.session_interface.is_null_session(ctx.session):1986- self.session_interface.save_session(self, ctx.session, response)1987-1988- return response1989-1990- def do_teardown_request(1991- self, exc: BaseException | None = _sentinel # type: ignore1992- ) -> None:1993- """Called after the request is dispatched and the response is1994- returned, right before the request context is popped.1995-1996- This calls all functions decorated with1997- :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`1998- if a blueprint handled the request. Finally, the1999- :data:`request_tearing_down` signal is sent.2000-2001- This is called by2002- :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,2003- which may be delayed during testing to maintain access to2004- resources.2005-2006- :param exc: An unhandled exception raised while dispatching the2007- request. Detected from the current exception information if2008- not passed. Passed to each teardown function.2009-2010- .. versionchanged:: 0.92011- Added the ``exc`` argument.2012- """2013- if exc is _sentinel:2014- exc = sys.exc_info()[1]2015-2016- for name in chain(request.blueprints, (None,)):2017- if name in self.teardown_request_funcs:2018- for func in reversed(self.teardown_request_funcs[name]):2019- self.ensure_sync(func)(exc)2020-2021- request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)2022-2023- def do_teardown_appcontext(2024- self, exc: BaseException | None = _sentinel # type: ignore2025- ) -> None:2026- """Called right before the application context is popped.2027-2028- When handling a request, the application context is popped2029- after the request context. See :meth:`do_teardown_request`.2030-2031- This calls all functions decorated with2032- :meth:`teardown_appcontext`. Then the2033- :data:`appcontext_tearing_down` signal is sent.2034-2035- This is called by2036- :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.2037-2038- .. versionadded:: 0.92039- """2040- if exc is _sentinel:2041- exc = sys.exc_info()[1]2042-2043- for func in reversed(self.teardown_appcontext_funcs):2044- self.ensure_sync(func)(exc)2045-2046- appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)2047-2048- def app_context(self) -> AppContext:2049- """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``2050- block to push the context, which will make :data:`current_app`2051- point at this application.2052-2053- An application context is automatically pushed by2054- :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`2055- when handling a request, and when running a CLI command. Use2056- this to manually create a context outside of these situations.2057-2058- ::2059-2060- with app.app_context():2061- init_db()2062-2063- See :doc:`/appcontext`.2064-2065- .. versionadded:: 0.92066- """2067- return AppContext(self)2068-2069- def request_context(self, environ: dict) -> RequestContext:2070- """Create a :class:`~flask.ctx.RequestContext` representing a2071- WSGI environment. Use a ``with`` block to push the context,2072- which will make :data:`request` point at this request.2073-2074- See :doc:`/reqcontext`.2075-2076- Typically you should not call this from your own code. A request2077- context is automatically pushed by the :meth:`wsgi_app` when2078- handling a request. Use :meth:`test_request_context` to create2079- an environment and context instead of this method.2080-2081- :param environ: a WSGI environment2082- """2083- return RequestContext(self, environ)2084-2085- def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:2086- """Create a :class:`~flask.ctx.RequestContext` for a WSGI2087- environment created from the given values. This is mostly useful2088- during testing, where you may want to run a function that uses2089- request data without dispatching a full request.2090-2091- See :doc:`/reqcontext`.2092-2093- Use a ``with`` block to push the context, which will make2094- :data:`request` point at the request for the created2095- environment. ::2096-2097- with app.test_request_context(...):2098- generate_report()2099-2100- When using the shell, it may be easier to push and pop the2101- context manually to avoid indentation. ::2102-2103- ctx = app.test_request_context(...)2104- ctx.push()2105- ...2106- ctx.pop()2107-2108- Takes the same arguments as Werkzeug's2109- :class:`~werkzeug.test.EnvironBuilder`, with some defaults from2110- the application. See the linked Werkzeug docs for most of the2111- available arguments. Flask-specific behavior is listed here.2112-2113- :param path: URL path being requested.2114- :param base_url: Base URL where the app is being served, which2115- ``path`` is relative to. If not given, built from2116- :data:`PREFERRED_URL_SCHEME`, ``subdomain``,2117- :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.2118- :param subdomain: Subdomain name to append to2119- :data:`SERVER_NAME`.2120- :param url_scheme: Scheme to use instead of2121- :data:`PREFERRED_URL_SCHEME`.2122- :param data: The request body, either as a string or a dict of2123- form keys and values.2124- :param json: If given, this is serialized as JSON and passed as2125- ``data``. Also defaults ``content_type`` to2126- ``application/json``.2127- :param args: other positional arguments passed to2128- :class:`~werkzeug.test.EnvironBuilder`.2129- :param kwargs: other keyword arguments passed to2130- :class:`~werkzeug.test.EnvironBuilder`.2131- """2132- from .testing import EnvironBuilder2133-2134- builder = EnvironBuilder(self, *args, **kwargs)2135-2136- try:2137- return self.request_context(builder.get_environ())2138- finally:2139- builder.close()2140-2141- def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:2142- """The actual WSGI application. This is not implemented in2143- :meth:`__call__` so that middlewares can be applied without2144- losing a reference to the app object. Instead of doing this::2145-2146- app = MyMiddleware(app)2147-2148- It's a better idea to do this instead::2149-2150- app.wsgi_app = MyMiddleware(app.wsgi_app)2151-2152- Then you still have the original application object around and2153- can continue to call methods on it.2154-2155- .. versionchanged:: 0.72156- Teardown events for the request and app contexts are called2157- even if an unhandled error occurs. Other events may not be2158- called depending on when an error occurs during dispatch.2159- See :ref:`callbacks-and-errors`.2160-2161- :param environ: A WSGI environment.2162- :param start_response: A callable accepting a status code,2163- a list of headers, and an optional exception context to2164- start the response.2165- """2166- ctx = self.request_context(environ)2167- error: BaseException | None = None2168- try:2169- try:2170- ctx.push()2171- response = self.full_dispatch_request()2172- except Exception as e:2173- error = e2174- response = self.handle_exception(e)2175- except: # noqa: B0012176- error = sys.exc_info()[1]2177- raise2178- return response(environ, start_response)2179- finally:2180- if "werkzeug.debug.preserve_context" in environ:2181- environ["werkzeug.debug.preserve_context"](_cv_app.get())2182- environ["werkzeug.debug.preserve_context"](_cv_request.get())2183-2184- if error is not None and self.should_ignore_error(error):2185- error = None2186-2187- ctx.pop(error)2188-2189- def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:2190- """The WSGI server calls the Flask application object as the2191- WSGI application. This calls :meth:`wsgi_app`, which can be2192- wrapped to apply middleware.2193- """2194- return self.wsgi_app(environ, start_response)modified:src/flask/sansio/blueprints.py+6 added-6 removed
3 unmodified lines4 import typing as t5 from collections import defaultdict6 from functools import update_wrapper7 8-from . import typing as ft8+from .. import typing as ft9 from .scaffold import _endpoint_from_view_func10 from .scaffold import _sentinel11 from .scaffold import Scaffold12 from .scaffold import setupmethod13 14 if t.TYPE_CHECKING: # pragma: no cover15- from .app import Flask15+ from .app import App16 17 DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]18 T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)19 T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)20 unmodified lines40 41 def __init__(42 self,43 blueprint: Blueprint,44- app: Flask,44+ app: App,45 options: t.Any,46 first_registration: bool,47 ) -> None:48 #: a reference to the current application194 unmodified lines243 244 self.record(update_wrapper(wrapper, func))245 246 def make_setup_state(247- self, app: Flask, options: dict, first_registration: bool = False247+ self, app: App, options: dict, first_registration: bool = False248 ) -> BlueprintSetupState:249 """Creates an instance of :meth:`~flask.blueprints.BlueprintSetupState`250 object that is later passed to the register callback functions.251 Subclasses can override this to return a subclass of the setup state.17 unmodified lines269 if blueprint is self:270 raise ValueError("Cannot register a blueprint on itself")271 self._blueprints.append((blueprint, options))272 273- def register(self, app: Flask, options: dict) -> None:273+ def register(self, app: App, options: dict) -> None:274 """Called by :meth:`Flask.register_blueprint` to register all275 views and callbacks registered on the blueprint with the276 application. Creates a :class:`.BlueprintSetupState` and calls277 each :meth:`record` callback with it.44 unmodified lines322 323 if self.has_static_folder:324 state.add_url_rule(325 f"{self.static_url_path}/<path:filename>",326- view_func=self.send_static_file,326+ view_func=self.send_static_file, # type: ignore[attr-defined]327 endpoint="static",328 )329 330 # Merge blueprint data into parent.296 unmodified linesmodified:src/flask/sansio/scaffold.py+4 added-75 removed
4 unmodified lines5 import pathlib6 import sys7 import typing as t8 from collections import defaultdict9-from datetime import timedelta9 from functools import update_wrapper10 11 from jinja2 import FileSystemLoader12 from werkzeug.exceptions import default_exceptions13 from werkzeug.exceptions import HTTPException14 from werkzeug.utils import cached_property15 17-from . import typing as ft18-from .cli import AppGroup19-from .globals import current_app20-from .helpers import get_root_path21-from .helpers import send_from_directory22-from .templating import _default_template_ctx_processor16+from .. import typing as ft17+from ..cli import AppGroup18+from ..helpers import get_root_path19+from ..templating import _default_template_ctx_processor20 24-if t.TYPE_CHECKING: # pragma: no cover25- from .wrappers import Response26-21 # a singleton sentinel value for parameter defaults22 _sentinel = object()23 24 F = t.TypeVar("F", bound=t.Callable[..., t.Any])244 unmodified lines269 value = value.rstrip("/")270 271 self._static_url_path = value272 279- def get_send_file_max_age(self, filename: str | None) -> int | None:280- """Used by :func:`send_file` to determine the ``max_age`` cache281- value for a given file path if it wasn't passed.282-283- By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from284- the configuration of :data:`~flask.current_app`. This defaults285- to ``None``, which tells the browser to use conditional requests286- instead of a timed cache, which is usually preferable.287-288- .. versionchanged:: 2.0289- The default configuration is ``None`` instead of 12 hours.290-291- .. versionadded:: 0.9292- """293- value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]294-295- if value is None:296- return None297-298- if isinstance(value, timedelta):299- return int(value.total_seconds())300-301- return value302-303- def send_static_file(self, filename: str) -> Response:304- """The view function used to serve files from305- :attr:`static_folder`. A route is automatically registered for306- this view at :attr:`static_url_path` if :attr:`static_folder` is307- set.308-309- .. versionadded:: 0.5310- """311- if not self.has_static_folder:312- raise RuntimeError("'static_folder' must be set to serve static_files.")313-314- # send_file only knows to call get_send_file_max_age on the app,315- # call it here so it works for blueprints too.316- max_age = self.get_send_file_max_age(filename)317- return send_from_directory(318- t.cast(str, self.static_folder), filename, max_age=max_age319- )320-273 @cached_property274 def jinja_loader(self) -> FileSystemLoader | None:275 """The Jinja loader for this object's templates. By default this276 is a class :class:`jinja2.loaders.FileSystemLoader` to5 unmodified lines282 return FileSystemLoader(os.path.join(self.root_path, self.template_folder))283 else:284 return None285 334- def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:335- """Open a resource file relative to :attr:`root_path` for336- reading.337-338- For example, if the file ``schema.sql`` is next to the file339- ``app.py`` where the ``Flask`` app is defined, it can be opened340- with:341-342- .. code-block:: python343-344- with app.open_resource("schema.sql") as f:345- conn.executescript(f.read())346-347- :param resource: Path to the resource relative to348- :attr:`root_path`.349- :param mode: Open the file in this mode. Only reading is350- supported, valid values are "r" (or "rt") and "rb".351- """352- if mode not in {"r", "rt", "rb"}:353- raise ValueError("Resources can only be opened for reading.")354-355- return open(os.path.join(self.root_path, resource), mode)356-286 def _method_route(287 self,288 method: str,289 rule: str,513 unmodified linesmodified:src/flask/__init__.py+2 added-2 removed
1 from . import json as json2 from .app import Flask as Flask3-from .app import Request as Request4-from .app import Response as Response3 from .blueprints import Blueprint as Blueprint4 from .config import Config as Config5 from .ctx import after_this_request as after_this_request6 from .ctx import copy_current_request_context as copy_current_request_context27 unmodified lines34 from .templating import render_template as render_template35 from .templating import render_template_string as render_template_string36 from .templating import stream_template as stream_template37 from .templating import stream_template_string as stream_template_string38+from .wrappers import Request as Request39+from .wrappers import Response as Response40 41 __version__ = "3.0.0.dev"added:src/flask/app.py+1478 added
1+from __future__ import annotations2+3+import os4+import sys5+import typing as t6+import weakref7+from collections.abc import Iterator as _abc_Iterator8+from datetime import timedelta9+from inspect import iscoroutinefunction10+from itertools import chain11+from types import TracebackType12+from urllib.parse import quote as _url_quote13+14+import click15+from werkzeug.datastructures import Headers16+from werkzeug.datastructures import ImmutableDict17+from werkzeug.exceptions import BadRequestKeyError18+from werkzeug.exceptions import HTTPException19+from werkzeug.exceptions import InternalServerError20+from werkzeug.routing import BuildError21+from werkzeug.routing import MapAdapter22+from werkzeug.routing import RequestRedirect23+from werkzeug.routing import RoutingException24+from werkzeug.routing import Rule25+from werkzeug.serving import is_running_from_reloader26+from werkzeug.wrappers import Response as BaseResponse27+28+from . import cli29+from . import typing as ft30+from .ctx import AppContext31+from .ctx import RequestContext32+from .globals import _cv_app33+from .globals import _cv_request34+from .globals import current_app35+from .globals import g36+from .globals import request37+from .globals import request_ctx38+from .globals import session39+from .helpers import get_debug_flag40+from .helpers import get_flashed_messages41+from .helpers import get_load_dotenv42+from .helpers import send_from_directory43+from .sansio.app import App44+from .sansio.scaffold import _sentinel45+from .sessions import SecureCookieSessionInterface46+from .sessions import SessionInterface47+from .signals import appcontext_tearing_down48+from .signals import got_request_exception49+from .signals import request_finished50+from .signals import request_started51+from .signals import request_tearing_down52+from .templating import Environment53+from .wrappers import Request54+from .wrappers import Response55+56+if t.TYPE_CHECKING: # pragma: no cover57+ from .testing import FlaskClient58+ from .testing import FlaskCliRunner59+60+T_shell_context_processor = t.TypeVar(61+ "T_shell_context_processor", bound=ft.ShellContextProcessorCallable62+)63+T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)64+T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)65+T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)66+T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)67+68+69+def _make_timedelta(value: timedelta | int | None) -> timedelta | None:70+ if value is None or isinstance(value, timedelta):71+ return value72+73+ return timedelta(seconds=value)74+75+76+class Flask(App):77+ """The flask object implements a WSGI application and acts as the central78+ object. It is passed the name of the module or package of the79+ application. Once it is created it will act as a central registry for80+ the view functions, the URL rules, template configuration and much more.81+82+ The name of the package is used to resolve resources from inside the83+ package or the folder the module is contained in depending on if the84+ package parameter resolves to an actual python package (a folder with85+ an :file:`__init__.py` file inside) or a standard module (just a ``.py`` file).86+87+ For more information about resource loading, see :func:`open_resource`.88+89+ Usually you create a :class:`Flask` instance in your main module or90+ in the :file:`__init__.py` file of your package like this::91+92+ from flask import Flask93+ app = Flask(__name__)94+95+ .. admonition:: About the First Parameter96+97+ The idea of the first parameter is to give Flask an idea of what98+ belongs to your application. This name is used to find resources99+ on the filesystem, can be used by extensions to improve debugging100+ information and a lot more.101+102+ So it's important what you provide there. If you are using a single103+ module, `__name__` is always the correct value. If you however are104+ using a package, it's usually recommended to hardcode the name of105+ your package there.106+107+ For example if your application is defined in :file:`yourapplication/app.py`108+ you should create it with one of the two versions below::109+110+ app = Flask('yourapplication')111+ app = Flask(__name__.split('.')[0])112+113+ Why is that? The application will work even with `__name__`, thanks114+ to how resources are looked up. However it will make debugging more115+ painful. Certain extensions can make assumptions based on the116+ import name of your application. For example the Flask-SQLAlchemy117+ extension will look for the code in your application that triggered118+ an SQL query in debug mode. If the import name is not properly set119+ up, that debugging information is lost. (For example it would only120+ pick up SQL queries in `yourapplication.app` and not121+ `yourapplication.views.frontend`)122+123+ .. versionadded:: 0.7124+ The `static_url_path`, `static_folder`, and `template_folder`125+ parameters were added.126+127+ .. versionadded:: 0.8128+ The `instance_path` and `instance_relative_config` parameters were129+ added.130+131+ .. versionadded:: 0.11132+ The `root_path` parameter was added.133+134+ .. versionadded:: 1.0135+ The ``host_matching`` and ``static_host`` parameters were added.136+137+ .. versionadded:: 1.0138+ The ``subdomain_matching`` parameter was added. Subdomain139+ matching needs to be enabled manually now. Setting140+ :data:`SERVER_NAME` does not implicitly enable it.141+142+ :param import_name: the name of the application package143+ :param static_url_path: can be used to specify a different path for the144+ static files on the web. Defaults to the name145+ of the `static_folder` folder.146+ :param static_folder: The folder with static files that is served at147+ ``static_url_path``. Relative to the application ``root_path``148+ or an absolute path. Defaults to ``'static'``.149+ :param static_host: the host to use when adding the static route.150+ Defaults to None. Required when using ``host_matching=True``151+ with a ``static_folder`` configured.152+ :param host_matching: set ``url_map.host_matching`` attribute.153+ Defaults to False.154+ :param subdomain_matching: consider the subdomain relative to155+ :data:`SERVER_NAME` when matching routes. Defaults to False.156+ :param template_folder: the folder that contains the templates that should157+ be used by the application. Defaults to158+ ``'templates'`` folder in the root path of the159+ application.160+ :param instance_path: An alternative instance path for the application.161+ By default the folder ``'instance'`` next to the162+ package or module is assumed to be the instance163+ path.164+ :param instance_relative_config: if set to ``True`` relative filenames165+ for loading the config are assumed to166+ be relative to the instance path instead167+ of the application root.168+ :param root_path: The path to the root of the application files.169+ This should only be set manually when it can't be detected170+ automatically, such as for namespace packages.171+ """172+173+ default_config = ImmutableDict(174+ {175+ "DEBUG": None,176+ "TESTING": False,177+ "PROPAGATE_EXCEPTIONS": None,178+ "SECRET_KEY": None,179+ "PERMANENT_SESSION_LIFETIME": timedelta(days=31),180+ "USE_X_SENDFILE": False,181+ "SERVER_NAME": None,182+ "APPLICATION_ROOT": "/",183+ "SESSION_COOKIE_NAME": "session",184+ "SESSION_COOKIE_DOMAIN": None,185+ "SESSION_COOKIE_PATH": None,186+ "SESSION_COOKIE_HTTPONLY": True,187+ "SESSION_COOKIE_SECURE": False,188+ "SESSION_COOKIE_SAMESITE": None,189+ "SESSION_REFRESH_EACH_REQUEST": True,190+ "MAX_CONTENT_LENGTH": None,191+ "SEND_FILE_MAX_AGE_DEFAULT": None,192+ "TRAP_BAD_REQUEST_ERRORS": None,193+ "TRAP_HTTP_EXCEPTIONS": False,194+ "EXPLAIN_TEMPLATE_LOADING": False,195+ "PREFERRED_URL_SCHEME": "http",196+ "TEMPLATES_AUTO_RELOAD": None,197+ "MAX_COOKIE_SIZE": 4093,198+ }199+ )200+201+ #: The class that is used for request objects. See :class:`~flask.Request`202+ #: for more information.203+ request_class = Request204+205+ #: The class that is used for response objects. See206+ #: :class:`~flask.Response` for more information.207+ response_class = Response208+209+ #: the session interface to use. By default an instance of210+ #: :class:`~flask.sessions.SecureCookieSessionInterface` is used here.211+ #:212+ #: .. versionadded:: 0.8213+ session_interface: SessionInterface = SecureCookieSessionInterface()214+215+ def __init__(216+ self,217+ import_name: str,218+ static_url_path: str | None = None,219+ static_folder: str | os.PathLike | None = "static",220+ static_host: str | None = None,221+ host_matching: bool = False,222+ subdomain_matching: bool = False,223+ template_folder: str | os.PathLike | None = "templates",224+ instance_path: str | None = None,225+ instance_relative_config: bool = False,226+ root_path: str | None = None,227+ ):228+ super().__init__(229+ import_name=import_name,230+ static_url_path=static_url_path,231+ static_folder=static_folder,232+ static_host=static_host,233+ host_matching=host_matching,234+ subdomain_matching=subdomain_matching,235+ template_folder=template_folder,236+ instance_path=instance_path,237+ instance_relative_config=instance_relative_config,238+ root_path=root_path,239+ )240+241+ # Add a static route using the provided static_url_path, static_host,242+ # and static_folder if there is a configured static_folder.243+ # Note we do this without checking if static_folder exists.244+ # For one, it might be created while the server is running (e.g. during245+ # development). Also, Google App Engine stores static files somewhere246+ if self.has_static_folder:247+ assert (248+ bool(static_host) == host_matching249+ ), "Invalid static_host/host_matching combination"250+ # Use a weakref to avoid creating a reference cycle between the app251+ # and the view function (see #3761).252+ self_ref = weakref.ref(self)253+ self.add_url_rule(254+ f"{self.static_url_path}/<path:filename>",255+ endpoint="static",256+ host=static_host,257+ view_func=lambda **kw: self_ref().send_static_file(**kw), # type: ignore # noqa: B950258+ )259+260+ def get_send_file_max_age(self, filename: str | None) -> int | None:261+ """Used by :func:`send_file` to determine the ``max_age`` cache262+ value for a given file path if it wasn't passed.263+264+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from265+ the configuration of :data:`~flask.current_app`. This defaults266+ to ``None``, which tells the browser to use conditional requests267+ instead of a timed cache, which is usually preferable.268+269+ Note this is a duplicate of the same method in the Flask270+ class.271+272+ .. versionchanged:: 2.0273+ The default configuration is ``None`` instead of 12 hours.274+275+ .. versionadded:: 0.9276+ """277+ value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]278+279+ if value is None:280+ return None281+282+ if isinstance(value, timedelta):283+ return int(value.total_seconds())284+285+ return value286+287+ def send_static_file(self, filename: str) -> Response:288+ """The view function used to serve files from289+ :attr:`static_folder`. A route is automatically registered for290+ this view at :attr:`static_url_path` if :attr:`static_folder` is291+ set.292+293+ Note this is a duplicate of the same method in the Flask294+ class.295+296+ .. versionadded:: 0.5297+298+ """299+ if not self.has_static_folder:300+ raise RuntimeError("'static_folder' must be set to serve static_files.")301+302+ # send_file only knows to call get_send_file_max_age on the app,303+ # call it here so it works for blueprints too.304+ max_age = self.get_send_file_max_age(filename)305+ return send_from_directory(306+ t.cast(str, self.static_folder), filename, max_age=max_age307+ )308+309+ def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:310+ """Open a resource file relative to :attr:`root_path` for311+ reading.312+313+ For example, if the file ``schema.sql`` is next to the file314+ ``app.py`` where the ``Flask`` app is defined, it can be opened315+ with:316+317+ .. code-block:: python318+319+ with app.open_resource("schema.sql") as f:320+ conn.executescript(f.read())321+322+ :param resource: Path to the resource relative to323+ :attr:`root_path`.324+ :param mode: Open the file in this mode. Only reading is325+ supported, valid values are "r" (or "rt") and "rb".326+327+ Note this is a duplicate of the same method in the Flask328+ class.329+330+ """331+ if mode not in {"r", "rt", "rb"}:332+ raise ValueError("Resources can only be opened for reading.")333+334+ return open(os.path.join(self.root_path, resource), mode)335+336+ def open_instance_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:337+ """Opens a resource from the application's instance folder338+ (:attr:`instance_path`). Otherwise works like339+ :meth:`open_resource`. Instance resources can also be opened for340+ writing.341+342+ :param resource: the name of the resource. To access resources within343+ subfolders use forward slashes as separator.344+ :param mode: resource file opening mode, default is 'rb'.345+ """346+ return open(os.path.join(self.instance_path, resource), mode)347+348+ def create_jinja_environment(self) -> Environment:349+ """Create the Jinja environment based on :attr:`jinja_options`350+ and the various Jinja-related methods of the app. Changing351+ :attr:`jinja_options` after this will have no effect. Also adds352+ Flask-related globals and filters to the environment.353+354+ .. versionchanged:: 0.11355+ ``Environment.auto_reload`` set in accordance with356+ ``TEMPLATES_AUTO_RELOAD`` configuration option.357+358+ .. versionadded:: 0.5359+ """360+ options = dict(self.jinja_options)361+362+ if "autoescape" not in options:363+ options["autoescape"] = self.select_jinja_autoescape364+365+ if "auto_reload" not in options:366+ auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]367+368+ if auto_reload is None:369+ auto_reload = self.debug370+371+ options["auto_reload"] = auto_reload372+373+ rv = self.jinja_environment(self, **options)374+ rv.globals.update(375+ url_for=self.url_for,376+ get_flashed_messages=get_flashed_messages,377+ config=self.config,378+ # request, session and g are normally added with the379+ # context processor for efficiency reasons but for imported380+ # templates we also want the proxies in there.381+ request=request,382+ session=session,383+ g=g,384+ )385+ rv.policies["json.dumps_function"] = self.json.dumps386+ return rv387+388+ def create_url_adapter(self, request: Request | None) -> MapAdapter | None:389+ """Creates a URL adapter for the given request. The URL adapter390+ is created at a point where the request context is not yet set391+ up so the request is passed explicitly.392+393+ .. versionadded:: 0.6394+395+ .. versionchanged:: 0.9396+ This can now also be called without a request object when the397+ URL adapter is created for the application context.398+399+ .. versionchanged:: 1.0400+ :data:`SERVER_NAME` no longer implicitly enables subdomain401+ matching. Use :attr:`subdomain_matching` instead.402+ """403+ if request is not None:404+ # If subdomain matching is disabled (the default), use the405+ # default subdomain in all cases. This should be the default406+ # in Werkzeug but it currently does not have that feature.407+ if not self.subdomain_matching:408+ subdomain = self.url_map.default_subdomain or None409+ else:410+ subdomain = None411+412+ print(self.config["SERVER_NAME"], subdomain)413+ return self.url_map.bind_to_environ(414+ request.environ,415+ server_name=self.config["SERVER_NAME"],416+ subdomain=subdomain,417+ )418+ # We need at the very least the server name to be set for this419+ # to work.420+ if self.config["SERVER_NAME"] is not None:421+ return self.url_map.bind(422+ self.config["SERVER_NAME"],423+ script_name=self.config["APPLICATION_ROOT"],424+ url_scheme=self.config["PREFERRED_URL_SCHEME"],425+ )426+427+ return None428+429+ def raise_routing_exception(self, request: Request) -> t.NoReturn:430+ """Intercept routing exceptions and possibly do something else.431+432+ In debug mode, intercept a routing redirect and replace it with433+ an error if the body will be discarded.434+435+ With modern Werkzeug this shouldn't occur, since it now uses a436+ 308 status which tells the browser to resend the method and437+ body.438+439+ .. versionchanged:: 2.1440+ Don't intercept 307 and 308 redirects.441+442+ :meta private:443+ :internal:444+ """445+ if (446+ not self.debug447+ or not isinstance(request.routing_exception, RequestRedirect)448+ or request.routing_exception.code in {307, 308}449+ or request.method in {"GET", "HEAD", "OPTIONS"}450+ ):451+ raise request.routing_exception # type: ignore452+453+ from .debughelpers import FormDataRoutingRedirect454+455+ raise FormDataRoutingRedirect(request)456+457+ def update_template_context(self, context: dict) -> None:458+ """Update the template context with some commonly used variables.459+ This injects request, session, config and g into the template460+ context as well as everything template context processors want461+ to inject. Note that the as of Flask 0.6, the original values462+ in the context will not be overridden if a context processor463+ decides to return a value with the same key.464+465+ :param context: the context as a dictionary that is updated in place466+ to add extra variables.467+ """468+ names: t.Iterable[str | None] = (None,)469+470+ # A template may be rendered outside a request context.471+ if request:472+ names = chain(names, reversed(request.blueprints))473+474+ # The values passed to render_template take precedence. Keep a475+ # copy to re-apply after all context functions.476+ orig_ctx = context.copy()477+478+ for name in names:479+ if name in self.template_context_processors:480+ for func in self.template_context_processors[name]:481+ context.update(func())482+483+ context.update(orig_ctx)484+485+ def make_shell_context(self) -> dict:486+ """Returns the shell context for an interactive shell for this487+ application. This runs all the registered shell context488+ processors.489+490+ .. versionadded:: 0.11491+ """492+ rv = {"app": self, "g": g}493+ for processor in self.shell_context_processors:494+ rv.update(processor())495+ return rv496+497+ def run(498+ self,499+ host: str | None = None,500+ port: int | None = None,501+ debug: bool | None = None,502+ load_dotenv: bool = True,503+ **options: t.Any,504+ ) -> None:505+ """Runs the application on a local development server.506+507+ Do not use ``run()`` in a production setting. It is not intended to508+ meet security and performance requirements for a production server.509+ Instead, see :doc:`/deploying/index` for WSGI server recommendations.510+511+ If the :attr:`debug` flag is set the server will automatically reload512+ for code changes and show a debugger in case an exception happened.513+514+ If you want to run the application in debug mode, but disable the515+ code execution on the interactive debugger, you can pass516+ ``use_evalex=False`` as parameter. This will keep the debugger's517+ traceback screen active, but disable code execution.518+519+ It is not recommended to use this function for development with520+ automatic reloading as this is badly supported. Instead you should521+ be using the :command:`flask` command line script's ``run`` support.522+523+ .. admonition:: Keep in Mind524+525+ Flask will suppress any server error with a generic error page526+ unless it is in debug mode. As such to enable just the527+ interactive debugger without the code reloading, you have to528+ invoke :meth:`run` with ``debug=True`` and ``use_reloader=False``.529+ Setting ``use_debugger`` to ``True`` without being in debug mode530+ won't catch any exceptions because there won't be any to531+ catch.532+533+ :param host: the hostname to listen on. Set this to ``'0.0.0.0'`` to534+ have the server available externally as well. Defaults to535+ ``'127.0.0.1'`` or the host in the ``SERVER_NAME`` config variable536+ if present.537+ :param port: the port of the webserver. Defaults to ``5000`` or the538+ port defined in the ``SERVER_NAME`` config variable if present.539+ :param debug: if given, enable or disable debug mode. See540+ :attr:`debug`.541+ :param load_dotenv: Load the nearest :file:`.env` and :file:`.flaskenv`542+ files to set environment variables. Will also change the working543+ directory to the directory containing the first file found.544+ :param options: the options to be forwarded to the underlying Werkzeug545+ server. See :func:`werkzeug.serving.run_simple` for more546+ information.547+548+ .. versionchanged:: 1.0549+ If installed, python-dotenv will be used to load environment550+ variables from :file:`.env` and :file:`.flaskenv` files.551+552+ The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.553+554+ Threaded mode is enabled by default.555+556+ .. versionchanged:: 0.10557+ The default port is now picked from the ``SERVER_NAME``558+ variable.559+ """560+ # Ignore this call so that it doesn't start another server if561+ # the 'flask run' command is used.562+ if os.environ.get("FLASK_RUN_FROM_CLI") == "true":563+ if not is_running_from_reloader():564+ click.secho(565+ " * Ignoring a call to 'app.run()' that would block"566+ " the current 'flask' CLI command.\n"567+ " Only call 'app.run()' in an 'if __name__ =="568+ ' "__main__"\' guard.',569+ fg="red",570+ )571+572+ return573+574+ if get_load_dotenv(load_dotenv):575+ cli.load_dotenv()576+577+ # if set, env var overrides existing value578+ if "FLASK_DEBUG" in os.environ:579+ self.debug = get_debug_flag()580+581+ # debug passed to method overrides all other sources582+ if debug is not None:583+ self.debug = bool(debug)584+585+ server_name = self.config.get("SERVER_NAME")586+ sn_host = sn_port = None587+588+ if server_name:589+ sn_host, _, sn_port = server_name.partition(":")590+591+ if not host:592+ if sn_host:593+ host = sn_host594+ else:595+ host = "127.0.0.1"596+597+ if port or port == 0:598+ port = int(port)599+ elif sn_port:600+ port = int(sn_port)601+ else:602+ port = 5000603+604+ options.setdefault("use_reloader", self.debug)605+ options.setdefault("use_debugger", self.debug)606+ options.setdefault("threaded", True)607+608+ cli.show_server_banner(self.debug, self.name)609+610+ from werkzeug.serving import run_simple611+612+ try:613+ run_simple(t.cast(str, host), port, self, **options)614+ finally:615+ # reset the first request information if the development server616+ # reset normally. This makes it possible to restart the server617+ # without reloader and that stuff from an interactive shell.618+ self._got_first_request = False619+620+ def test_client(self, use_cookies: bool = True, **kwargs: t.Any) -> FlaskClient:621+ """Creates a test client for this application. For information622+ about unit testing head over to :doc:`/testing`.623+624+ Note that if you are testing for assertions or exceptions in your625+ application code, you must set ``app.testing = True`` in order for the626+ exceptions to propagate to the test client. Otherwise, the exception627+ will be handled by the application (not visible to the test client) and628+ the only indication of an AssertionError or other exception will be a629+ 500 status code response to the test client. See the :attr:`testing`630+ attribute. For example::631+632+ app.testing = True633+ client = app.test_client()634+635+ The test client can be used in a ``with`` block to defer the closing down636+ of the context until the end of the ``with`` block. This is useful if637+ you want to access the context locals for testing::638+639+ with app.test_client() as c:640+ rv = c.get('/?vodka=42')641+ assert request.args['vodka'] == '42'642+643+ Additionally, you may pass optional keyword arguments that will then644+ be passed to the application's :attr:`test_client_class` constructor.645+ For example::646+647+ from flask.testing import FlaskClient648+649+ class CustomClient(FlaskClient):650+ def __init__(self, *args, **kwargs):651+ self._authentication = kwargs.pop("authentication")652+ super(CustomClient,self).__init__( *args, **kwargs)653+654+ app.test_client_class = CustomClient655+ client = app.test_client(authentication='Basic ....')656+657+ See :class:`~flask.testing.FlaskClient` for more information.658+659+ .. versionchanged:: 0.4660+ added support for ``with`` block usage for the client.661+662+ .. versionadded:: 0.7663+ The `use_cookies` parameter was added as well as the ability664+ to override the client to be used by setting the665+ :attr:`test_client_class` attribute.666+667+ .. versionchanged:: 0.11668+ Added `**kwargs` to support passing additional keyword arguments to669+ the constructor of :attr:`test_client_class`.670+ """671+ cls = self.test_client_class672+ if cls is None:673+ from .testing import FlaskClient as cls674+ return cls( # type: ignore675+ self, self.response_class, use_cookies=use_cookies, **kwargs676+ )677+678+ def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:679+ """Create a CLI runner for testing CLI commands.680+ See :ref:`testing-cli`.681+682+ Returns an instance of :attr:`test_cli_runner_class`, by default683+ :class:`~flask.testing.FlaskCliRunner`. The Flask app object is684+ passed as the first argument.685+686+ .. versionadded:: 1.0687+ """688+ cls = self.test_cli_runner_class689+690+ if cls is None:691+ from .testing import FlaskCliRunner as cls692+693+ return cls(self, **kwargs) # type: ignore694+695+ def handle_http_exception(696+ self, e: HTTPException697+ ) -> HTTPException | ft.ResponseReturnValue:698+ """Handles an HTTP exception. By default this will invoke the699+ registered error handlers and fall back to returning the700+ exception as response.701+702+ .. versionchanged:: 1.0.3703+ ``RoutingException``, used internally for actions such as704+ slash redirects during routing, is not passed to error705+ handlers.706+707+ .. versionchanged:: 1.0708+ Exceptions are looked up by code *and* by MRO, so709+ ``HTTPException`` subclasses can be handled with a catch-all710+ handler for the base ``HTTPException``.711+712+ .. versionadded:: 0.3713+ """714+ # Proxy exceptions don't have error codes. We want to always return715+ # those unchanged as errors716+ if e.code is None:717+ return e718+719+ # RoutingExceptions are used internally to trigger routing720+ # actions, such as slash redirects raising RequestRedirect. They721+ # are not raised or handled in user code.722+ if isinstance(e, RoutingException):723+ return e724+725+ handler = self._find_error_handler(e, request.blueprints)726+ if handler is None:727+ return e728+ return self.ensure_sync(handler)(e)729+730+ def handle_user_exception(731+ self, e: Exception732+ ) -> HTTPException | ft.ResponseReturnValue:733+ """This method is called whenever an exception occurs that734+ should be handled. A special case is :class:`~werkzeug735+ .exceptions.HTTPException` which is forwarded to the736+ :meth:`handle_http_exception` method. This function will either737+ return a response value or reraise the exception with the same738+ traceback.739+740+ .. versionchanged:: 1.0741+ Key errors raised from request data like ``form`` show the742+ bad key in debug mode rather than a generic bad request743+ message.744+745+ .. versionadded:: 0.7746+ """747+ if isinstance(e, BadRequestKeyError) and (748+ self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]749+ ):750+ e.show_exception = True751+752+ if isinstance(e, HTTPException) and not self.trap_http_exception(e):753+ return self.handle_http_exception(e)754+755+ handler = self._find_error_handler(e, request.blueprints)756+757+ if handler is None:758+ raise759+760+ return self.ensure_sync(handler)(e)761+762+ def handle_exception(self, e: Exception) -> Response:763+ """Handle an exception that did not have an error handler764+ associated with it, or that was raised from an error handler.765+ This always causes a 500 ``InternalServerError``.766+767+ Always sends the :data:`got_request_exception` signal.768+769+ If :data:`PROPAGATE_EXCEPTIONS` is ``True``, such as in debug770+ mode, the error will be re-raised so that the debugger can771+ display it. Otherwise, the original exception is logged, and772+ an :exc:`~werkzeug.exceptions.InternalServerError` is returned.773+774+ If an error handler is registered for ``InternalServerError`` or775+ ``500``, it will be used. For consistency, the handler will776+ always receive the ``InternalServerError``. The original777+ unhandled exception is available as ``e.original_exception``.778+779+ .. versionchanged:: 1.1.0780+ Always passes the ``InternalServerError`` instance to the781+ handler, setting ``original_exception`` to the unhandled782+ error.783+784+ .. versionchanged:: 1.1.0785+ ``after_request`` functions and other finalization is done786+ even for the default 500 response when there is no handler.787+788+ .. versionadded:: 0.3789+ """790+ exc_info = sys.exc_info()791+ got_request_exception.send(self, _async_wrapper=self.ensure_sync, exception=e)792+ propagate = self.config["PROPAGATE_EXCEPTIONS"]793+794+ if propagate is None:795+ propagate = self.testing or self.debug796+797+ if propagate:798+ # Re-raise if called with an active exception, otherwise799+ # raise the passed in exception.800+ if exc_info[1] is e:801+ raise802+803+ raise e804+805+ self.log_exception(exc_info)806+ server_error: InternalServerError | ft.ResponseReturnValue807+ server_error = InternalServerError(original_exception=e)808+ handler = self._find_error_handler(server_error, request.blueprints)809+810+ if handler is not None:811+ server_error = self.ensure_sync(handler)(server_error)812+813+ return self.finalize_request(server_error, from_error_handler=True)814+815+ def log_exception(816+ self,817+ exc_info: (tuple[type, BaseException, TracebackType] | tuple[None, None, None]),818+ ) -> None:819+ """Logs an exception. This is called by :meth:`handle_exception`820+ if debugging is disabled and right before the handler is called.821+ The default implementation logs the exception as error on the822+ :attr:`logger`.823+824+ .. versionadded:: 0.8825+ """826+ self.logger.error(827+ f"Exception on {request.path} [{request.method}]", exc_info=exc_info828+ )829+830+ def dispatch_request(self) -> ft.ResponseReturnValue:831+ """Does the request dispatching. Matches the URL and returns the832+ return value of the view or error handler. This does not have to833+ be a response object. In order to convert the return value to a834+ proper response object, call :func:`make_response`.835+836+ .. versionchanged:: 0.7837+ This no longer does the exception handling, this code was838+ moved to the new :meth:`full_dispatch_request`.839+ """840+ req = request_ctx.request841+ if req.routing_exception is not None:842+ self.raise_routing_exception(req)843+ rule: Rule = req.url_rule # type: ignore[assignment]844+ # if we provide automatic options for this URL and the845+ # request came with the OPTIONS method, reply automatically846+ if (847+ getattr(rule, "provide_automatic_options", False)848+ and req.method == "OPTIONS"849+ ):850+ return self.make_default_options_response()851+ # otherwise dispatch to the handler for that endpoint852+ view_args: dict[str, t.Any] = req.view_args # type: ignore[assignment]853+ return self.ensure_sync(self.view_functions[rule.endpoint])(**view_args)854+855+ def full_dispatch_request(self) -> Response:856+ """Dispatches the request and on top of that performs request857+ pre and postprocessing as well as HTTP exception catching and858+ error handling.859+860+ .. versionadded:: 0.7861+ """862+ self._got_first_request = True863+864+ try:865+ request_started.send(self, _async_wrapper=self.ensure_sync)866+ rv = self.preprocess_request()867+ if rv is None:868+ rv = self.dispatch_request()869+ except Exception as e:870+ rv = self.handle_user_exception(e)871+ return self.finalize_request(rv)872+873+ def finalize_request(874+ self,875+ rv: ft.ResponseReturnValue | HTTPException,876+ from_error_handler: bool = False,877+ ) -> Response:878+ """Given the return value from a view function this finalizes879+ the request by converting it into a response and invoking the880+ postprocessing functions. This is invoked for both normal881+ request dispatching as well as error handlers.882+883+ Because this means that it might be called as a result of a884+ failure a special safe mode is available which can be enabled885+ with the `from_error_handler` flag. If enabled, failures in886+ response processing will be logged and otherwise ignored.887+888+ :internal:889+ """890+ response = self.make_response(rv)891+ try:892+ response = self.process_response(response)893+ request_finished.send(894+ self, _async_wrapper=self.ensure_sync, response=response895+ )896+ except Exception:897+ if not from_error_handler:898+ raise899+ self.logger.exception(900+ "Request finalizing failed with an error while handling an error"901+ )902+ return response903+904+ def make_default_options_response(self) -> Response:905+ """This method is called to create the default ``OPTIONS`` response.906+ This can be changed through subclassing to change the default907+ behavior of ``OPTIONS`` responses.908+909+ .. versionadded:: 0.7910+ """911+ adapter = request_ctx.url_adapter912+ methods = adapter.allowed_methods() # type: ignore[union-attr]913+ rv = self.response_class()914+ rv.allow.update(methods)915+ return rv916+917+ def ensure_sync(self, func: t.Callable) -> t.Callable:918+ """Ensure that the function is synchronous for WSGI workers.919+ Plain ``def`` functions are returned as-is. ``async def``920+ functions are wrapped to run and wait for the response.921+922+ Override this method to change how the app runs async views.923+924+ .. versionadded:: 2.0925+ """926+ if iscoroutinefunction(func):927+ return self.async_to_sync(func)928+929+ return func930+931+ def async_to_sync(932+ self, func: t.Callable[..., t.Coroutine]933+ ) -> t.Callable[..., t.Any]:934+ """Return a sync function that will run the coroutine function.935+936+ .. code-block:: python937+938+ result = app.async_to_sync(func)(*args, **kwargs)939+940+ Override this method to change how the app converts async code941+ to be synchronously callable.942+943+ .. versionadded:: 2.0944+ """945+ try:946+ from asgiref.sync import async_to_sync as asgiref_async_to_sync947+ except ImportError:948+ raise RuntimeError(949+ "Install Flask with the 'async' extra in order to use async views."950+ ) from None951+952+ return asgiref_async_to_sync(func)953+954+ def url_for(955+ self,956+ endpoint: str,957+ *,958+ _anchor: str | None = None,959+ _method: str | None = None,960+ _scheme: str | None = None,961+ _external: bool | None = None,962+ **values: t.Any,963+ ) -> str:964+ """Generate a URL to the given endpoint with the given values.965+966+ This is called by :func:`flask.url_for`, and can be called967+ directly as well.968+969+ An *endpoint* is the name of a URL rule, usually added with970+ :meth:`@app.route() <route>`, and usually the same name as the971+ view function. A route defined in a :class:`~flask.Blueprint`972+ will prepend the blueprint's name separated by a ``.`` to the973+ endpoint.974+975+ In some cases, such as email messages, you want URLs to include976+ the scheme and domain, like ``https://example.com/hello``. When977+ not in an active request, URLs will be external by default, but978+ this requires setting :data:`SERVER_NAME` so Flask knows what979+ domain to use. :data:`APPLICATION_ROOT` and980+ :data:`PREFERRED_URL_SCHEME` should also be configured as981+ needed. This config is only used when not in an active request.982+983+ Functions can be decorated with :meth:`url_defaults` to modify984+ keyword arguments before the URL is built.985+986+ If building fails for some reason, such as an unknown endpoint987+ or incorrect values, the app's :meth:`handle_url_build_error`988+ method is called. If that returns a string, that is returned,989+ otherwise a :exc:`~werkzeug.routing.BuildError` is raised.990+991+ :param endpoint: The endpoint name associated with the URL to992+ generate. If this starts with a ``.``, the current blueprint993+ name (if any) will be used.994+ :param _anchor: If given, append this as ``#anchor`` to the URL.995+ :param _method: If given, generate the URL associated with this996+ method for the endpoint.997+ :param _scheme: If given, the URL will have this scheme if it998+ is external.999+ :param _external: If given, prefer the URL to be internal1000+ (False) or require it to be external (True). External URLs1001+ include the scheme and domain. When not in an active1002+ request, URLs are external by default.1003+ :param values: Values to use for the variable parts of the URL1004+ rule. Unknown keys are appended as query string arguments,1005+ like ``?a=b&c=d``.1006+1007+ .. versionadded:: 2.21008+ Moved from ``flask.url_for``, which calls this method.1009+ """1010+ req_ctx = _cv_request.get(None)1011+1012+ if req_ctx is not None:1013+ url_adapter = req_ctx.url_adapter1014+ blueprint_name = req_ctx.request.blueprint1015+1016+ # If the endpoint starts with "." and the request matches a1017+ # blueprint, the endpoint is relative to the blueprint.1018+ if endpoint[:1] == ".":1019+ if blueprint_name is not None:1020+ endpoint = f"{blueprint_name}{endpoint}"1021+ else:1022+ endpoint = endpoint[1:]1023+1024+ # When in a request, generate a URL without scheme and1025+ # domain by default, unless a scheme is given.1026+ if _external is None:1027+ _external = _scheme is not None1028+ else:1029+ app_ctx = _cv_app.get(None)1030+1031+ # If called by helpers.url_for, an app context is active,1032+ # use its url_adapter. Otherwise, app.url_for was called1033+ # directly, build an adapter.1034+ if app_ctx is not None:1035+ url_adapter = app_ctx.url_adapter1036+ else:1037+ url_adapter = self.create_url_adapter(None)1038+1039+ if url_adapter is None:1040+ raise RuntimeError(1041+ "Unable to build URLs outside an active request"1042+ " without 'SERVER_NAME' configured. Also configure"1043+ " 'APPLICATION_ROOT' and 'PREFERRED_URL_SCHEME' as"1044+ " needed."1045+ )1046+1047+ # When outside a request, generate a URL with scheme and1048+ # domain by default.1049+ if _external is None:1050+ _external = True1051+1052+ # It is an error to set _scheme when _external=False, in order1053+ # to avoid accidental insecure URLs.1054+ if _scheme is not None and not _external:1055+ raise ValueError("When specifying '_scheme', '_external' must be True.")1056+1057+ self.inject_url_defaults(endpoint, values)1058+1059+ try:1060+ rv = url_adapter.build( # type: ignore[union-attr]1061+ endpoint,1062+ values,1063+ method=_method,1064+ url_scheme=_scheme,1065+ force_external=_external,1066+ )1067+ except BuildError as error:1068+ values.update(1069+ _anchor=_anchor, _method=_method, _scheme=_scheme, _external=_external1070+ )1071+ return self.handle_url_build_error(error, endpoint, values)1072+1073+ if _anchor is not None:1074+ _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")1075+ rv = f"{rv}#{_anchor}"1076+1077+ return rv1078+1079+ def make_response(self, rv: ft.ResponseReturnValue) -> Response:1080+ """Convert the return value from a view function to an instance of1081+ :attr:`response_class`.1082+1083+ :param rv: the return value from the view function. The view function1084+ must return a response. Returning ``None``, or the view ending1085+ without returning, is not allowed. The following types are allowed1086+ for ``view_rv``:1087+1088+ ``str``1089+ A response object is created with the string encoded to UTF-81090+ as the body.1091+1092+ ``bytes``1093+ A response object is created with the bytes as the body.1094+1095+ ``dict``1096+ A dictionary that will be jsonify'd before being returned.1097+1098+ ``list``1099+ A list that will be jsonify'd before being returned.1100+1101+ ``generator`` or ``iterator``1102+ A generator that returns ``str`` or ``bytes`` to be1103+ streamed as the response.1104+1105+ ``tuple``1106+ Either ``(body, status, headers)``, ``(body, status)``, or1107+ ``(body, headers)``, where ``body`` is any of the other types1108+ allowed here, ``status`` is a string or an integer, and1109+ ``headers`` is a dictionary or a list of ``(key, value)``1110+ tuples. If ``body`` is a :attr:`response_class` instance,1111+ ``status`` overwrites the exiting value and ``headers`` are1112+ extended.1113+1114+ :attr:`response_class`1115+ The object is returned unchanged.1116+1117+ other :class:`~werkzeug.wrappers.Response` class1118+ The object is coerced to :attr:`response_class`.1119+1120+ :func:`callable`1121+ The function is called as a WSGI application. The result is1122+ used to create a response object.1123+1124+ .. versionchanged:: 2.21125+ A generator will be converted to a streaming response.1126+ A list will be converted to a JSON response.1127+1128+ .. versionchanged:: 1.11129+ A dict will be converted to a JSON response.1130+1131+ .. versionchanged:: 0.91132+ Previously a tuple was interpreted as the arguments for the1133+ response object.1134+ """1135+1136+ status = headers = None1137+1138+ # unpack tuple returns1139+ if isinstance(rv, tuple):1140+ len_rv = len(rv)1141+1142+ # a 3-tuple is unpacked directly1143+ if len_rv == 3:1144+ rv, status, headers = rv # type: ignore[misc]1145+ # decide if a 2-tuple has status or headers1146+ elif len_rv == 2:1147+ if isinstance(rv[1], (Headers, dict, tuple, list)):1148+ rv, headers = rv1149+ else:1150+ rv, status = rv # type: ignore[assignment,misc]1151+ # other sized tuples are not allowed1152+ else:1153+ raise TypeError(1154+ "The view function did not return a valid response tuple."1155+ " The tuple must have the form (body, status, headers),"1156+ " (body, status), or (body, headers)."1157+ )1158+1159+ # the body must not be None1160+ if rv is None:1161+ raise TypeError(1162+ f"The view function for {request.endpoint!r} did not"1163+ " return a valid response. The function either returned"1164+ " None or ended without a return statement."1165+ )1166+1167+ # make sure the body is an instance of the response class1168+ if not isinstance(rv, self.response_class):1169+ if isinstance(rv, (str, bytes, bytearray)) or isinstance(rv, _abc_Iterator):1170+ # let the response class set the status and headers instead of1171+ # waiting to do it manually, so that the class can handle any1172+ # special logic1173+ rv = self.response_class(1174+ rv,1175+ status=status,1176+ headers=headers, # type: ignore[arg-type]1177+ )1178+ status = headers = None1179+ elif isinstance(rv, (dict, list)):1180+ rv = self.json.response(rv)1181+ elif isinstance(rv, BaseResponse) or callable(rv):1182+ # evaluate a WSGI callable, or coerce a different response1183+ # class to the correct type1184+ try:1185+ rv = self.response_class.force_type(1186+ rv, request.environ # type: ignore[arg-type]1187+ )1188+ except TypeError as e:1189+ raise TypeError(1190+ f"{e}\nThe view function did not return a valid"1191+ " response. The return type must be a string,"1192+ " dict, list, tuple with headers or status,"1193+ " Response instance, or WSGI callable, but it"1194+ f" was a {type(rv).__name__}."1195+ ).with_traceback(sys.exc_info()[2]) from None1196+ else:1197+ raise TypeError(1198+ "The view function did not return a valid"1199+ " response. The return type must be a string,"1200+ " dict, list, tuple with headers or status,"1201+ " Response instance, or WSGI callable, but it was a"1202+ f" {type(rv).__name__}."1203+ )1204+1205+ rv = t.cast(Response, rv)1206+ # prefer the status if it was provided1207+ if status is not None:1208+ if isinstance(status, (str, bytes, bytearray)):1209+ rv.status = status1210+ else:1211+ rv.status_code = status1212+1213+ # extend existing headers with provided headers1214+ if headers:1215+ rv.headers.update(headers) # type: ignore[arg-type]1216+1217+ return rv1218+1219+ def preprocess_request(self) -> ft.ResponseReturnValue | None:1220+ """Called before the request is dispatched. Calls1221+ :attr:`url_value_preprocessors` registered with the app and the1222+ current blueprint (if any). Then calls :attr:`before_request_funcs`1223+ registered with the app and the blueprint.1224+1225+ If any :meth:`before_request` handler returns a non-None value, the1226+ value is handled as if it was the return value from the view, and1227+ further request handling is stopped.1228+ """1229+ names = (None, *reversed(request.blueprints))1230+1231+ for name in names:1232+ if name in self.url_value_preprocessors:1233+ for url_func in self.url_value_preprocessors[name]:1234+ url_func(request.endpoint, request.view_args)1235+1236+ for name in names:1237+ if name in self.before_request_funcs:1238+ for before_func in self.before_request_funcs[name]:1239+ rv = self.ensure_sync(before_func)()1240+1241+ if rv is not None:1242+ return rv1243+1244+ return None1245+1246+ def process_response(self, response: Response) -> Response:1247+ """Can be overridden in order to modify the response object1248+ before it's sent to the WSGI server. By default this will1249+ call all the :meth:`after_request` decorated functions.1250+1251+ .. versionchanged:: 0.51252+ As of Flask 0.5 the functions registered for after request1253+ execution are called in reverse order of registration.1254+1255+ :param response: a :attr:`response_class` object.1256+ :return: a new response object or the same, has to be an1257+ instance of :attr:`response_class`.1258+ """1259+ ctx = request_ctx._get_current_object() # type: ignore[attr-defined]1260+1261+ for func in ctx._after_request_functions:1262+ response = self.ensure_sync(func)(response)1263+1264+ for name in chain(request.blueprints, (None,)):1265+ if name in self.after_request_funcs:1266+ for func in reversed(self.after_request_funcs[name]):1267+ response = self.ensure_sync(func)(response)1268+1269+ if not self.session_interface.is_null_session(ctx.session):1270+ self.session_interface.save_session(self, ctx.session, response)1271+1272+ return response1273+1274+ def do_teardown_request(1275+ self, exc: BaseException | None = _sentinel # type: ignore1276+ ) -> None:1277+ """Called after the request is dispatched and the response is1278+ returned, right before the request context is popped.1279+1280+ This calls all functions decorated with1281+ :meth:`teardown_request`, and :meth:`Blueprint.teardown_request`1282+ if a blueprint handled the request. Finally, the1283+ :data:`request_tearing_down` signal is sent.1284+1285+ This is called by1286+ :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,1287+ which may be delayed during testing to maintain access to1288+ resources.1289+1290+ :param exc: An unhandled exception raised while dispatching the1291+ request. Detected from the current exception information if1292+ not passed. Passed to each teardown function.1293+1294+ .. versionchanged:: 0.91295+ Added the ``exc`` argument.1296+ """1297+ if exc is _sentinel:1298+ exc = sys.exc_info()[1]1299+1300+ for name in chain(request.blueprints, (None,)):1301+ if name in self.teardown_request_funcs:1302+ for func in reversed(self.teardown_request_funcs[name]):1303+ self.ensure_sync(func)(exc)1304+1305+ request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1306+1307+ def do_teardown_appcontext(1308+ self, exc: BaseException | None = _sentinel # type: ignore1309+ ) -> None:1310+ """Called right before the application context is popped.1311+1312+ When handling a request, the application context is popped1313+ after the request context. See :meth:`do_teardown_request`.1314+1315+ This calls all functions decorated with1316+ :meth:`teardown_appcontext`. Then the1317+ :data:`appcontext_tearing_down` signal is sent.1318+1319+ This is called by1320+ :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.1321+1322+ .. versionadded:: 0.91323+ """1324+ if exc is _sentinel:1325+ exc = sys.exc_info()[1]1326+1327+ for func in reversed(self.teardown_appcontext_funcs):1328+ self.ensure_sync(func)(exc)1329+1330+ appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)1331+1332+ def app_context(self) -> AppContext:1333+ """Create an :class:`~flask.ctx.AppContext`. Use as a ``with``1334+ block to push the context, which will make :data:`current_app`1335+ point at this application.1336+1337+ An application context is automatically pushed by1338+ :meth:`RequestContext.push() <flask.ctx.RequestContext.push>`1339+ when handling a request, and when running a CLI command. Use1340+ this to manually create a context outside of these situations.1341+1342+ ::1343+1344+ with app.app_context():1345+ init_db()1346+1347+ See :doc:`/appcontext`.1348+1349+ .. versionadded:: 0.91350+ """1351+ return AppContext(self)1352+1353+ def request_context(self, environ: dict) -> RequestContext:1354+ """Create a :class:`~flask.ctx.RequestContext` representing a1355+ WSGI environment. Use a ``with`` block to push the context,1356+ which will make :data:`request` point at this request.1357+1358+ See :doc:`/reqcontext`.1359+1360+ Typically you should not call this from your own code. A request1361+ context is automatically pushed by the :meth:`wsgi_app` when1362+ handling a request. Use :meth:`test_request_context` to create1363+ an environment and context instead of this method.1364+1365+ :param environ: a WSGI environment1366+ """1367+ return RequestContext(self, environ)1368+1369+ def test_request_context(self, *args: t.Any, **kwargs: t.Any) -> RequestContext:1370+ """Create a :class:`~flask.ctx.RequestContext` for a WSGI1371+ environment created from the given values. This is mostly useful1372+ during testing, where you may want to run a function that uses1373+ request data without dispatching a full request.1374+1375+ See :doc:`/reqcontext`.1376+1377+ Use a ``with`` block to push the context, which will make1378+ :data:`request` point at the request for the created1379+ environment. ::1380+1381+ with app.test_request_context(...):1382+ generate_report()1383+1384+ When using the shell, it may be easier to push and pop the1385+ context manually to avoid indentation. ::1386+1387+ ctx = app.test_request_context(...)1388+ ctx.push()1389+ ...1390+ ctx.pop()1391+1392+ Takes the same arguments as Werkzeug's1393+ :class:`~werkzeug.test.EnvironBuilder`, with some defaults from1394+ the application. See the linked Werkzeug docs for most of the1395+ available arguments. Flask-specific behavior is listed here.1396+1397+ :param path: URL path being requested.1398+ :param base_url: Base URL where the app is being served, which1399+ ``path`` is relative to. If not given, built from1400+ :data:`PREFERRED_URL_SCHEME`, ``subdomain``,1401+ :data:`SERVER_NAME`, and :data:`APPLICATION_ROOT`.1402+ :param subdomain: Subdomain name to append to1403+ :data:`SERVER_NAME`.1404+ :param url_scheme: Scheme to use instead of1405+ :data:`PREFERRED_URL_SCHEME`.1406+ :param data: The request body, either as a string or a dict of1407+ form keys and values.1408+ :param json: If given, this is serialized as JSON and passed as1409+ ``data``. Also defaults ``content_type`` to1410+ ``application/json``.1411+ :param args: other positional arguments passed to1412+ :class:`~werkzeug.test.EnvironBuilder`.1413+ :param kwargs: other keyword arguments passed to1414+ :class:`~werkzeug.test.EnvironBuilder`.1415+ """1416+ from .testing import EnvironBuilder1417+1418+ builder = EnvironBuilder(self, *args, **kwargs)1419+1420+ try:1421+ return self.request_context(builder.get_environ())1422+ finally:1423+ builder.close()1424+1425+ def wsgi_app(self, environ: dict, start_response: t.Callable) -> t.Any:1426+ """The actual WSGI application. This is not implemented in1427+ :meth:`__call__` so that middlewares can be applied without1428+ losing a reference to the app object. Instead of doing this::1429+1430+ app = MyMiddleware(app)1431+1432+ It's a better idea to do this instead::1433+1434+ app.wsgi_app = MyMiddleware(app.wsgi_app)1435+1436+ Then you still have the original application object around and1437+ can continue to call methods on it.1438+1439+ .. versionchanged:: 0.71440+ Teardown events for the request and app contexts are called1441+ even if an unhandled error occurs. Other events may not be1442+ called depending on when an error occurs during dispatch.1443+ See :ref:`callbacks-and-errors`.1444+1445+ :param environ: A WSGI environment.1446+ :param start_response: A callable accepting a status code,1447+ a list of headers, and an optional exception context to1448+ start the response.1449+ """1450+ ctx = self.request_context(environ)1451+ error: BaseException | None = None1452+ try:1453+ try:1454+ ctx.push()1455+ response = self.full_dispatch_request()1456+ except Exception as e:1457+ error = e1458+ response = self.handle_exception(e)1459+ except: # noqa: B0011460+ error = sys.exc_info()[1]1461+ raise1462+ return response(environ, start_response)1463+ finally:1464+ if "werkzeug.debug.preserve_context" in environ:1465+ environ["werkzeug.debug.preserve_context"](_cv_app.get())1466+ environ["werkzeug.debug.preserve_context"](_cv_request.get())1467+1468+ if error is not None and self.should_ignore_error(error):1469+ error = None1470+1471+ ctx.pop(error)1472+1473+ def __call__(self, environ: dict, start_response: t.Callable) -> t.Any:1474+ """The WSGI server calls the Flask application object as the1475+ WSGI application. This calls :meth:`wsgi_app`, which can be1476+ wrapped to apply middleware.1477+ """1478+ return self.wsgi_app(environ, start_response)added:src/flask/blueprints.py+91 added
1+from __future__ import annotations2+3+import os4+import typing as t5+from datetime import timedelta6+7+from .globals import current_app8+from .helpers import send_from_directory9+from .sansio.blueprints import Blueprint as SansioBlueprint10+from .sansio.blueprints import BlueprintSetupState as BlueprintSetupState # noqa11+12+if t.TYPE_CHECKING: # pragma: no cover13+ from .wrappers import Response14+15+16+class Blueprint(SansioBlueprint):17+ def get_send_file_max_age(self, filename: str | None) -> int | None:18+ """Used by :func:`send_file` to determine the ``max_age`` cache19+ value for a given file path if it wasn't passed.20+21+ By default, this returns :data:`SEND_FILE_MAX_AGE_DEFAULT` from22+ the configuration of :data:`~flask.current_app`. This defaults23+ to ``None``, which tells the browser to use conditional requests24+ instead of a timed cache, which is usually preferable.25+26+ Note this is a duplicate of the same method in the Flask27+ class.28+29+ .. versionchanged:: 2.030+ The default configuration is ``None`` instead of 12 hours.31+32+ .. versionadded:: 0.933+ """34+ value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]35+36+ if value is None:37+ return None38+39+ if isinstance(value, timedelta):40+ return int(value.total_seconds())41+42+ return value43+44+ def send_static_file(self, filename: str) -> Response:45+ """The view function used to serve files from46+ :attr:`static_folder`. A route is automatically registered for47+ this view at :attr:`static_url_path` if :attr:`static_folder` is48+ set.49+50+ Note this is a duplicate of the same method in the Flask51+ class.52+53+ .. versionadded:: 0.554+55+ """56+ if not self.has_static_folder:57+ raise RuntimeError("'static_folder' must be set to serve static_files.")58+59+ # send_file only knows to call get_send_file_max_age on the app,60+ # call it here so it works for blueprints too.61+ max_age = self.get_send_file_max_age(filename)62+ return send_from_directory(63+ t.cast(str, self.static_folder), filename, max_age=max_age64+ )65+66+ def open_resource(self, resource: str, mode: str = "rb") -> t.IO[t.AnyStr]:67+ """Open a resource file relative to :attr:`root_path` for68+ reading.69+70+ For example, if the file ``schema.sql`` is next to the file71+ ``app.py`` where the ``Flask`` app is defined, it can be opened72+ with:73+74+ .. code-block:: python75+76+ with app.open_resource("schema.sql") as f:77+ conn.executescript(f.read())78+79+ :param resource: Path to the resource relative to80+ :attr:`root_path`.81+ :param mode: Open the file in this mode. Only reading is82+ supported, valid values are "r" (or "rt") and "rb".83+84+ Note this is a duplicate of the same method in the Flask85+ class.86+87+ """88+ if mode not in {"r", "rt", "rb"}:89+ raise ValueError("Resources can only be opened for reading.")90+91+ return open(os.path.join(self.root_path, resource), mode)modified:src/flask/debughelpers.py+3 added-3 removed
1 from __future__ import annotations2 3 import typing as t4 5-from .app import Flask5 from .blueprints import Blueprint6 from .globals import request_ctx7+from .sansio.app import App8 9 10 class UnexpectedUnicodeError(AssertionError, UnicodeError):11 """Raised in places where we want some better error reporting for100 unmodified lines112 continue113 yield f"{key}: {value!r}"114 115 116-def explain_template_loading_attempts(app: Flask, template, attempts) -> None:116+def explain_template_loading_attempts(app: App, template, attempts) -> None:117 """This should help developers understand what failed"""118 info = [f"Locating template {template!r}:"]119 total_found = 0120 blueprint = None121 if request_ctx and request_ctx.request.blueprint is not None:122 blueprint = request_ctx.request.blueprint123 124 for idx, (loader, srcobj, triple) in enumerate(attempts):125- if isinstance(srcobj, Flask):125+ if isinstance(srcobj, App):126 src_info = f"application {srcobj.import_name!r}"127 elif isinstance(srcobj, Blueprint):128 src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"129 else:31 unmodified linesmodified:src/flask/logging.py+2 added-2 removed
7 unmodified lines8 9 from .globals import request10 11 if t.TYPE_CHECKING: # pragma: no cover12- from .app import Flask12+ from .sansio.app import App13 14 15 @LocalProxy16 def wsgi_errors_stream() -> t.TextIO:34 unmodified lines51 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")52 )53 54 55-def create_logger(app: Flask) -> logging.Logger:55+def create_logger(app: App) -> logging.Logger:56 """Get the Flask app's logger and configure it if needed.57 58 The logger name will be the same as59 :attr:`app.import_name <flask.Flask.name>`.17 unmodified linesmodified:src/flask/templating.py+4 added-3 removed
15 unmodified lines16 from .signals import template_rendered17 18 if t.TYPE_CHECKING: # pragma: no cover19 from .app import Flask20+ from .sansio.app import App20- from .scaffold import Scaffold21+ from .sansio.scaffold import Scaffold22 23 24 def _default_template_ctx_processor() -> dict[str, t.Any]:25 """Default template context processor. Injects `request`,15 unmodified lines41 knowledge of how Flask's blueprint works so that it can prepend the42 name of the blueprint to referenced templates if necessary.43 """44 44- def __init__(self, app: Flask, **options: t.Any) -> None:45+ def __init__(self, app: App, **options: t.Any) -> None:46 if "loader" not in options:47 options["loader"] = app.create_global_jinja_loader()48 BaseEnvironment.__init__(self, **options)49 self.app = app3 unmodified lines53 """A loader that looks for templates in the application and all54 the blueprint folders.55 """56 56- def __init__(self, app: Flask) -> None:57+ def __init__(self, app: App) -> None:58 self.app = app59 60 def get_source( # type: ignore61 self, environment: Environment, template: str160 unmodified lines