Skip to content
Myr

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

10 files+1621 added−1352 removed

modified:src/flask/json/provider.py+2 added-2 removed
9 unmodified lines
1011from werkzeug.http import http_date1213if t.TYPE_CHECKING: # pragma: no cover14 from ..app import Flask14 from ..sansio.app import App15 from ..wrappers import Response161718class JSONProvider:
14 unmodified lines
3334 .. versionadded:: 2.235 """3637 def __init__(self, app: Flask) -> None:37 def __init__(self, app: App) -> None:38 self._app = weakref.proxy(app)3940 def dumps(self, obj: t.Any, **kwargs: t.Any) -> str:41 """Serialize data as JSON.
175 unmodified lines
modified:src/flask/sansio/app.py+29 added-1259 removed
2 unmodified lines
3import logging4import os5import sys6import typing as t7import weakref8from collections.abc import Iterator as _abc_Iterator7from datetime import timedelta10from inspect import iscoroutinefunction8from itertools import chain12from types import TracebackType13from urllib.parse import quote as _url_quote915import click16from werkzeug.datastructures import Headers17from werkzeug.datastructures import ImmutableDict10from werkzeug.exceptions import Aborter11from werkzeug.exceptions import BadRequest12from werkzeug.exceptions import BadRequestKeyError21from werkzeug.exceptions import HTTPException22from werkzeug.exceptions import InternalServerError13from werkzeug.routing import BuildError14from werkzeug.routing import Map25from werkzeug.routing import MapAdapter26from werkzeug.routing import RequestRedirect27from werkzeug.routing import RoutingException15from werkzeug.routing import Rule29from werkzeug.serving import is_running_from_reloader16from werkzeug.sansio.response import Response17from werkzeug.utils import cached_property18from werkzeug.utils import redirect as _wz_redirect32from werkzeug.wrappers import Response as BaseResponse1934from . import cli35from . import typing as ft36from .config import Config37from .config import ConfigAttribute38from .ctx import _AppCtxGlobals39from .ctx import AppContext40from .ctx import RequestContext41from .globals import _cv_app42from .globals import _cv_request43from .globals import g44from .globals import request45from .globals import request_ctx46from .globals import session47from .helpers import _split_blueprint_path48from .helpers import get_debug_flag49from .helpers import get_flashed_messages50from .helpers import get_load_dotenv51from .json.provider import DefaultJSONProvider52from .json.provider import JSONProvider53from .logging import create_logger20from .. import typing as ft21from ..config import Config22from ..config import ConfigAttribute23from ..ctx import _AppCtxGlobals24from ..helpers import _split_blueprint_path25from ..helpers import get_debug_flag26from ..json.provider import DefaultJSONProvider27from ..json.provider import JSONProvider28from ..logging import create_logger29from ..templating import DispatchingJinjaLoader30from ..templating import Environment31from .scaffold import _endpoint_from_view_func55from .scaffold import _sentinel32from .scaffold import find_package33from .scaffold import Scaffold34from .scaffold import setupmethod59from .sessions import SecureCookieSessionInterface60from .sessions import SessionInterface61from .signals import appcontext_tearing_down62from .signals import got_request_exception63from .signals import request_finished64from .signals import request_started65from .signals import request_tearing_down66from .templating import DispatchingJinjaLoader67from .templating import Environment68from .wrappers import Request69from .wrappers import Response3536if 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 FlaskCliRunner4142T_shell_context_processor = t.TypeVar(43 "T_shell_context_processor", bound=ft.ShellContextProcessorCallable44)
9 unmodified lines
5455 return timedelta(seconds=value)565792class Flask(Scaffold):58class 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 lines
151 This should only be set manually when it can't be detected152 automatically, such as for namespace packages.153 """154189 #: The class that is used for request objects. See :class:`~flask.Request`190 #: for more information.191 request_class = Request192193 #: The class that is used for response objects. See194 #: :class:`~flask.Response` for more information.195 response_class = Response196155 #: 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 lines
247 #: easier configuration.248 #:249 jinja_options: dict = {}250293 #: 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 )321251 #: 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.7
18 unmodified lines
273 #:274 #: .. versionadded:: 1.0275 test_cli_runner_class: type[FlaskCliRunner] | None = None276348 #: 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]279280 def __init__(281 self,282 import_name: str,
116 unmodified lines
399 #: 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)404479 self.url_map.host_matching = host_matching405 self.subdomain_matching = subdomain_matching406407 # tracks internally if the application already handled at least one408 # request.409 self._got_first_request = False410486 # 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 )504411 # 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 lines
477 effect.478 """479 return self.create_jinja_environment()480481 def create_jinja_environment(self) -> Environment:482 raise NotImplementedError()483484 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 if
33 unmodified lines
521 if prefix is None:522 return os.path.join(package_path, "instance")523 return os.path.join(prefix, "var", f"{self.name}-instance")524616 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.621622 :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)627628 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.633634 .. versionchanged:: 0.11635 ``Environment.auto_reload`` set in accordance with636 ``TEMPLATES_AUTO_RELOAD`` configuration option.637638 .. versionadded:: 0.5639 """640 options = dict(self.jinja_options)641642 if "autoescape" not in options:643 options["autoescape"] = self.select_jinja_autoescape644645 if "auto_reload" not in options:646 auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]647648 if auto_reload is None:649 auto_reload = self.debug650651 options["auto_reload"] = auto_reload652653 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 rv667525 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 override
18 unmodified lines
547 if filename is None:548 return True549 return filename.endswith((".html", ".htm", ".xml", ".xhtml", ".svg"))550694 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.701702 :param context: the context as a dictionary that is updated in place703 to add extra variables.704 """705 names: t.Iterable[str | None] = (None,)706707 # A template may be rendered outside a request context.708 if request:709 names = chain(names, reversed(request.blueprints))710711 # The values passed to render_template take precedence. Keep a712 # copy to re-apply after all context functions.713 orig_ctx = context.copy()714715 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())719720 context.update(orig_ctx)721722 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.726727 .. versionadded:: 0.11728 """729 rv = {"app": self, "g": g}730 for processor in self.shell_context_processors:731 rv.update(processor())732 return rv733551 @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 unhandled
12 unmodified lines
567568 if self.config["TEMPLATES_AUTO_RELOAD"] is None:569 self.jinja_env.auto_reload = value570754 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.763764 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.767768 If the :attr:`debug` flag is set the server will automatically reload769 for code changes and show a debugger in case an exception happened.770771 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.775776 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.779780 .. admonition:: Keep in Mind781782 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.789790 :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.804805 .. versionchanged:: 1.0806 If installed, python-dotenv will be used to load environment807 variables from :file:`.env` and :file:`.flaskenv` files.808809 The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.810811 Threaded mode is enabled by default.812813 .. 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 )828829 return830831 if get_load_dotenv(load_dotenv):832 cli.load_dotenv()833834 # if set, env var overrides existing value835 if "FLASK_DEBUG" in os.environ:836 self.debug = get_debug_flag()837838 # debug passed to method overrides all other sources839 if debug is not None:840 self.debug = bool(debug)841842 server_name = self.config.get("SERVER_NAME")843 sn_host = sn_port = None844845 if server_name:846 sn_host, _, sn_port = server_name.partition(":")847848 if not host:849 if sn_host:850 host = sn_host851 else:852 host = "127.0.0.1"853854 if port or port == 0:855 port = int(port)856 elif sn_port:857 port = int(sn_port)858 else:859 port = 5000860861 options.setdefault("use_reloader", self.debug)862 options.setdefault("use_debugger", self.debug)863 options.setdefault("threaded", True)864865 cli.show_server_banner(self.debug, self.name)866867 from werkzeug.serving import run_simple868869 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 = False876877 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`.880881 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::888889 app.testing = True890 client = app.test_client()891892 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::895896 with app.test_client() as c:897 rv = c.get('/?vodka=42')898 assert request.args['vodka'] == '42'899900 Additionally, you may pass optional keyword arguments that will then901 be passed to the application's :attr:`test_client_class` constructor.902 For example::903904 from flask.testing import FlaskClient905906 class CustomClient(FlaskClient):907 def __init__(self, *args, **kwargs):908 self._authentication = kwargs.pop("authentication")909 super(CustomClient,self).__init__( *args, **kwargs)910911 app.test_client_class = CustomClient912 client = app.test_client(authentication='Basic ....')913914 See :class:`~flask.testing.FlaskClient` for more information.915916 .. versionchanged:: 0.4917 added support for ``with`` block usage for the client.918919 .. 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.923924 .. 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 )934935 def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:936 """Create a CLI runner for testing CLI commands.937 See :ref:`testing-cli`.938939 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.942943 .. versionadded:: 1.0944 """945 cls = self.test_cli_runner_class946947 if cls is None:948 from .testing import FlaskCliRunner as cls949950 return cls(self, **kwargs) # type: ignore951571 @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 the
246 unmodified lines
821 """822 self.shell_context_processors.append(f)823 return f8241206 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)835836 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 lines
846 if handler is not None:847 return handler848 return None8491229 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.12351236 .. versionchanged:: 1.0.31237 ``RoutingException``, used internally for actions such as1238 slash redirects during routing, is not passed to error1239 handlers.12401241 .. 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``.12451246 .. 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 e12521253 # 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 e12581259 handler = self._find_error_handler(e)1260 if handler is None:1261 return e1262 return self.ensure_sync(handler)(e)1263850 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``. It
27 unmodified lines
881 return isinstance(e, BadRequest)882883 return False8841299 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.13081309 .. 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.13131314 .. versionadded:: 0.71315 """1316 if isinstance(e, BadRequestKeyError) and (1317 self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]1318 ):1319 e.show_exception = True13201321 if isinstance(e, HTTPException) and not self.trap_http_exception(e):1322 return self.handle_http_exception(e)13231324 handler = self._find_error_handler(e)13251326 if handler is None:1327 raise13281329 return self.ensure_sync(handler)(e)13301331 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``.13351336 Always sends the :data:`got_request_exception` signal.13371338 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.13421343 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``.13471348 .. versionchanged:: 1.1.01349 Always passes the ``InternalServerError`` instance to the1350 handler, setting ``original_exception`` to the unhandled1351 error.13521353 .. versionchanged:: 1.1.01354 ``after_request`` functions and other finalization is done1355 even for the default 500 response when there is no handler.13561357 .. 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"]13621363 if propagate is None:1364 propagate = self.testing or self.debug13651366 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 raise13711372 raise e13731374 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)13781379 if handler is not None:1380 server_error = self.ensure_sync(handler)(server_error)13811382 return self.finalize_request(server_error, from_error_handler=True)13831384 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`.13921393 .. versionadded:: 0.81394 """1395 self.logger.error(1396 f"Exception on {request.path} [{request.method}]", exc_info=exc_info1397 )13981399 def raise_routing_exception(self, request: Request) -> t.NoReturn:1400 """Intercept routing exceptions and possibly do something else.14011402 In debug mode, intercept a routing redirect and replace it with1403 an error if the body will be discarded.14041405 With modern Werkzeug this shouldn't occur, since it now uses a1406 308 status which tells the browser to resend the method and1407 body.14081409 .. versionchanged:: 2.11410 Don't intercept 307 and 308 redirects.14111412 :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: ignore14221423 from .debughelpers import FormDataRoutingRedirect14241425 raise FormDataRoutingRedirect(request)14261427 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`.14321433 .. 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)14511452 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.14561457 .. versionadded:: 0.71458 """1459 self._got_first_request = True14601461 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)14691470 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.14791480 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.14841485 :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 response15001501 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.15051506 .. 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 rv1513885 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 be
2 unmodified lines
891 .. versionadded:: 0.10892 """893 return False8941524 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.15281529 Override this method to change how the app runs async views.15301531 .. versionadded:: 2.01532 """1533 if iscoroutinefunction(func):1534 return self.async_to_sync(func)15351536 return func15371538 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.15421543 .. code-block:: python15441545 result = app.async_to_sync(func)(*args, **kwargs)15461547 Override this method to change how the app converts async code1548 to be synchronously callable.15491550 .. 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 None15581559 return asgiref_async_to_sync(func)15601561 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.15721573 This is called by :func:`flask.url_for`, and can be called1574 directly as well.15751576 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.15811582 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.15891590 Functions can be decorated with :meth:`url_defaults` to modify1591 keyword arguments before the URL is built.15921593 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.15971598 :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``.16131614 .. versionadded:: 2.21615 Moved from ``flask.url_for``, which calls this method.1616 """1617 req_ctx = _cv_request.get(None)16181619 if req_ctx is not None:1620 url_adapter = req_ctx.url_adapter1621 blueprint_name = req_ctx.request.blueprint16221623 # 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:]16301631 # 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)16371638 # 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)16451646 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 )16531654 # When outside a request, generate a URL with scheme and1655 # domain by default.1656 if _external is None:1657 _external = True16581659 # 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.")16631664 self.inject_url_defaults(endpoint, values)16651666 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)16791680 if _anchor is not None:1681 _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")1682 rv = f"{rv}#{_anchor}"16831684 return rv1685895 def redirect(self, location: str, code: int = 302) -> BaseResponse:896 """Create a redirect response object.897898 This is called by :func:`flask.redirect`, and can be called
4 unmodified lines
903904 .. 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 )9101700 def make_response(self, rv: ft.ResponseReturnValue) -> Response:1701 """Convert the return value from a view function to an instance of1702 :attr:`response_class`.17031704 :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``:17081709 ``str``1710 A response object is created with the string encoded to UTF-81711 as the body.17121713 ``bytes``1714 A response object is created with the bytes as the body.17151716 ``dict``1717 A dictionary that will be jsonify'd before being returned.17181719 ``list``1720 A list that will be jsonify'd before being returned.17211722 ``generator`` or ``iterator``1723 A generator that returns ``str`` or ``bytes`` to be1724 streamed as the response.17251726 ``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.17341735 :attr:`response_class`1736 The object is returned unchanged.17371738 other :class:`~werkzeug.wrappers.Response` class1739 The object is coerced to :attr:`response_class`.17401741 :func:`callable`1742 The function is called as a WSGI application. The result is1743 used to create a response object.17441745 .. versionchanged:: 2.21746 A generator will be converted to a streaming response.1747 A list will be converted to a JSON response.17481749 .. versionchanged:: 1.11750 A dict will be converted to a JSON response.17511752 .. versionchanged:: 0.91753 Previously a tuple was interpreted as the arguments for the1754 response object.1755 """17561757 status = headers = None17581759 # unpack tuple returns1760 if isinstance(rv, tuple):1761 len_rv = len(rv)17621763 # 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 )17791780 # 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 )17871788 # 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 )18251826 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 = status18331834 # extend existing headers with provided headers1835 if headers:1836 rv.headers.update(headers) # type: ignore[arg-type]18371838 return rv18391840 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.18441845 .. versionadded:: 0.618461847 .. versionchanged:: 0.91848 This can now also be called without a request object when the1849 URL adapter is created for the application context.18501851 .. 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 = None18631864 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 )18771878 return None1879911 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 lines
961 if error is sys.exc_info()[1]:962 raise963964 raise error19341935 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.19401941 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))19461947 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)19511952 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)()19561957 if rv is not None:1958 return rv19591960 return None19611962 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.19661967 .. versionchanged:: 0.51968 As of Flask 0.5 the functions registered for after request1969 execution are called in reverse order of registration.19701971 :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]19761977 for func in ctx._after_request_functions:1978 response = self.ensure_sync(func)(response)19791980 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)19841985 if not self.session_interface.is_null_session(ctx.session):1986 self.session_interface.save_session(self, ctx.session, response)19871988 return response19891990 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.19951996 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.20002001 This is called by2002 :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,2003 which may be delayed during testing to maintain access to2004 resources.20052006 :param exc: An unhandled exception raised while dispatching the2007 request. Detected from the current exception information if2008 not passed. Passed to each teardown function.20092010 .. versionchanged:: 0.92011 Added the ``exc`` argument.2012 """2013 if exc is _sentinel:2014 exc = sys.exc_info()[1]20152016 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)20202021 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)20222023 def do_teardown_appcontext(2024 self, exc: BaseException | None = _sentinel # type: ignore2025 ) -> None:2026 """Called right before the application context is popped.20272028 When handling a request, the application context is popped2029 after the request context. See :meth:`do_teardown_request`.20302031 This calls all functions decorated with2032 :meth:`teardown_appcontext`. Then the2033 :data:`appcontext_tearing_down` signal is sent.20342035 This is called by2036 :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.20372038 .. versionadded:: 0.92039 """2040 if exc is _sentinel:2041 exc = sys.exc_info()[1]20422043 for func in reversed(self.teardown_appcontext_funcs):2044 self.ensure_sync(func)(exc)20452046 appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)20472048 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.20522053 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.20572058 ::20592060 with app.app_context():2061 init_db()20622063 See :doc:`/appcontext`.20642065 .. versionadded:: 0.92066 """2067 return AppContext(self)20682069 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.20732074 See :doc:`/reqcontext`.20752076 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.20802081 :param environ: a WSGI environment2082 """2083 return RequestContext(self, environ)20842085 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.20902091 See :doc:`/reqcontext`.20922093 Use a ``with`` block to push the context, which will make2094 :data:`request` point at the request for the created2095 environment. ::20962097 with app.test_request_context(...):2098 generate_report()20992100 When using the shell, it may be easier to push and pop the2101 context manually to avoid indentation. ::21022103 ctx = app.test_request_context(...)2104 ctx.push()2105 ...2106 ctx.pop()21072108 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.21122113 :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 EnvironBuilder21332134 builder = EnvironBuilder(self, *args, **kwargs)21352136 try:2137 return self.request_context(builder.get_environ())2138 finally:2139 builder.close()21402141 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::21452146 app = MyMiddleware(app)21472148 It's a better idea to do this instead::21492150 app.wsgi_app = MyMiddleware(app.wsgi_app)21512152 Then you still have the original application object around and2153 can continue to call methods on it.21542155 .. 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`.21602161 :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())21832184 if error is not None and self.should_ignore_error(error):2185 error = None21862187 ctx.pop(error)21882189 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 lines
4import typing as t5from collections import defaultdict6from functools import update_wrapper78from . import typing as ft8from .. import typing as ft9from .scaffold import _endpoint_from_view_func10from .scaffold import _sentinel11from .scaffold import Scaffold12from .scaffold import setupmethod1314if t.TYPE_CHECKING: # pragma: no cover15 from .app import Flask15 from .app import App1617DeferredSetupFunction = t.Callable[["BlueprintSetupState"], t.Callable]18T_after_request = t.TypeVar("T_after_request", bound=ft.AfterRequestCallable)19T_before_request = t.TypeVar("T_before_request", bound=ft.BeforeRequestCallable)
20 unmodified lines
4041 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 application
194 unmodified lines
243244 self.record(update_wrapper(wrapper, func))245246 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 lines
269 if blueprint is self:270 raise ValueError("Cannot register a blueprint on itself")271 self._blueprints.append((blueprint, options))272273 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 lines
322323 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 )329330 # Merge blueprint data into parent.
296 unmodified lines
modified:src/flask/sansio/scaffold.py+4 added-75 removed
4 unmodified lines
5import pathlib6import sys7import typing as t8from collections import defaultdict9from datetime import timedelta9from functools import update_wrapper1011from jinja2 import FileSystemLoader12from werkzeug.exceptions import default_exceptions13from werkzeug.exceptions import HTTPException14from werkzeug.utils import cached_property1517from . import typing as ft18from .cli import AppGroup19from .globals import current_app20from .helpers import get_root_path21from .helpers import send_from_directory22from .templating import _default_template_ctx_processor16from .. import typing as ft17from ..cli import AppGroup18from ..helpers import get_root_path19from ..templating import _default_template_ctx_processor2024if t.TYPE_CHECKING: # pragma: no cover25 from .wrappers import Response2621# a singleton sentinel value for parameter defaults22_sentinel = object()2324F = t.TypeVar("F", bound=t.Callable[..., t.Any])
244 unmodified lines
269 value = value.rstrip("/")270271 self._static_url_path = value272279 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.282283 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.287288 .. versionchanged:: 2.0289 The default configuration is ``None`` instead of 12 hours.290291 .. versionadded:: 0.9292 """293 value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]294295 if value is None:296 return None297298 if isinstance(value, timedelta):299 return int(value.total_seconds())300301 return value302303 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.308309 .. versionadded:: 0.5310 """311 if not self.has_static_folder:312 raise RuntimeError("'static_folder' must be set to serve static_files.")313314 # 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 )320273 @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` to
5 unmodified lines
282 return FileSystemLoader(os.path.join(self.root_path, self.template_folder))283 else:284 return None285334 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.337338 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:341342 .. code-block:: python343344 with app.open_resource("schema.sql") as f:345 conn.executescript(f.read())346347 :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.")354355 return open(os.path.join(self.root_path, resource), mode)356286 def _method_route(287 self,288 method: str,289 rule: str,
513 unmodified lines
modified:src/flask/__init__.py+2 added-2 removed
1from . import json as json2from .app import Flask as Flask3from .app import Request as Request4from .app import Response as Response3from .blueprints import Blueprint as Blueprint4from .config import Config as Config5from .ctx import after_this_request as after_this_request6from .ctx import copy_current_request_context as copy_current_request_context
27 unmodified lines
34from .templating import render_template as render_template35from .templating import render_template_string as render_template_string36from .templating import stream_template as stream_template37from .templating import stream_template_string as stream_template_string38from .wrappers import Request as Request39from .wrappers import Response as Response4041__version__ = "3.0.0.dev"
added:src/flask/app.py+1478 added
1from __future__ import annotations23import os4import sys5import typing as t6import weakref7from collections.abc import Iterator as _abc_Iterator8from datetime import timedelta9from inspect import iscoroutinefunction10from itertools import chain11from types import TracebackType12from urllib.parse import quote as _url_quote1314import click15from werkzeug.datastructures import Headers16from werkzeug.datastructures import ImmutableDict17from werkzeug.exceptions import BadRequestKeyError18from werkzeug.exceptions import HTTPException19from werkzeug.exceptions import InternalServerError20from werkzeug.routing import BuildError21from werkzeug.routing import MapAdapter22from werkzeug.routing import RequestRedirect23from werkzeug.routing import RoutingException24from werkzeug.routing import Rule25from werkzeug.serving import is_running_from_reloader26from werkzeug.wrappers import Response as BaseResponse2728from . import cli29from . import typing as ft30from .ctx import AppContext31from .ctx import RequestContext32from .globals import _cv_app33from .globals import _cv_request34from .globals import current_app35from .globals import g36from .globals import request37from .globals import request_ctx38from .globals import session39from .helpers import get_debug_flag40from .helpers import get_flashed_messages41from .helpers import get_load_dotenv42from .helpers import send_from_directory43from .sansio.app import App44from .sansio.scaffold import _sentinel45from .sessions import SecureCookieSessionInterface46from .sessions import SessionInterface47from .signals import appcontext_tearing_down48from .signals import got_request_exception49from .signals import request_finished50from .signals import request_started51from .signals import request_tearing_down52from .templating import Environment53from .wrappers import Request54from .wrappers import Response5556if t.TYPE_CHECKING: # pragma: no cover57 from .testing import FlaskClient58 from .testing import FlaskCliRunner5960T_shell_context_processor = t.TypeVar(61 "T_shell_context_processor", bound=ft.ShellContextProcessorCallable62)63T_teardown = t.TypeVar("T_teardown", bound=ft.TeardownCallable)64T_template_filter = t.TypeVar("T_template_filter", bound=ft.TemplateFilterCallable)65T_template_global = t.TypeVar("T_template_global", bound=ft.TemplateGlobalCallable)66T_template_test = t.TypeVar("T_template_test", bound=ft.TemplateTestCallable)676869def _make_timedelta(value: timedelta | int | None) -> timedelta | None:70 if value is None or isinstance(value, timedelta):71 return value7273 return timedelta(seconds=value)747576class 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.8182 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).8687 For more information about resource loading, see :func:`open_resource`.8889 Usually you create a :class:`Flask` instance in your main module or90 in the :file:`__init__.py` file of your package like this::9192 from flask import Flask93 app = Flask(__name__)9495 .. admonition:: About the First Parameter9697 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.101102 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.106107 For example if your application is defined in :file:`yourapplication/app.py`108 you should create it with one of the two versions below::109110 app = Flask('yourapplication')111 app = Flask(__name__.split('.')[0])112113 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`)122123 .. versionadded:: 0.7124 The `static_url_path`, `static_folder`, and `template_folder`125 parameters were added.126127 .. versionadded:: 0.8128 The `instance_path` and `instance_relative_config` parameters were129 added.130131 .. versionadded:: 0.11132 The `root_path` parameter was added.133134 .. versionadded:: 1.0135 The ``host_matching`` and ``static_host`` parameters were added.136137 .. 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.141142 :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 """172173 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 )200201 #: The class that is used for request objects. See :class:`~flask.Request`202 #: for more information.203 request_class = Request204205 #: The class that is used for response objects. See206 #: :class:`~flask.Response` for more information.207 response_class = Response208209 #: 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()214215 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 )240241 # 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 )259260 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.263264 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.268269 Note this is a duplicate of the same method in the Flask270 class.271272 .. versionchanged:: 2.0273 The default configuration is ``None`` instead of 12 hours.274275 .. versionadded:: 0.9276 """277 value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]278279 if value is None:280 return None281282 if isinstance(value, timedelta):283 return int(value.total_seconds())284285 return value286287 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.292293 Note this is a duplicate of the same method in the Flask294 class.295296 .. versionadded:: 0.5297298 """299 if not self.has_static_folder:300 raise RuntimeError("'static_folder' must be set to serve static_files.")301302 # 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 )308309 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.312313 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:316317 .. code-block:: python318319 with app.open_resource("schema.sql") as f:320 conn.executescript(f.read())321322 :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".326327 Note this is a duplicate of the same method in the Flask328 class.329330 """331 if mode not in {"r", "rt", "rb"}:332 raise ValueError("Resources can only be opened for reading.")333334 return open(os.path.join(self.root_path, resource), mode)335336 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.341342 :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)347348 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.353354 .. versionchanged:: 0.11355 ``Environment.auto_reload`` set in accordance with356 ``TEMPLATES_AUTO_RELOAD`` configuration option.357358 .. versionadded:: 0.5359 """360 options = dict(self.jinja_options)361362 if "autoescape" not in options:363 options["autoescape"] = self.select_jinja_autoescape364365 if "auto_reload" not in options:366 auto_reload = self.config["TEMPLATES_AUTO_RELOAD"]367368 if auto_reload is None:369 auto_reload = self.debug370371 options["auto_reload"] = auto_reload372373 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 rv387388 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.392393 .. versionadded:: 0.6394395 .. versionchanged:: 0.9396 This can now also be called without a request object when the397 URL adapter is created for the application context.398399 .. 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 = None411412 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 )426427 return None428429 def raise_routing_exception(self, request: Request) -> t.NoReturn:430 """Intercept routing exceptions and possibly do something else.431432 In debug mode, intercept a routing redirect and replace it with433 an error if the body will be discarded.434435 With modern Werkzeug this shouldn't occur, since it now uses a436 308 status which tells the browser to resend the method and437 body.438439 .. versionchanged:: 2.1440 Don't intercept 307 and 308 redirects.441442 :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: ignore452453 from .debughelpers import FormDataRoutingRedirect454455 raise FormDataRoutingRedirect(request)456457 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.464465 :param context: the context as a dictionary that is updated in place466 to add extra variables.467 """468 names: t.Iterable[str | None] = (None,)469470 # A template may be rendered outside a request context.471 if request:472 names = chain(names, reversed(request.blueprints))473474 # The values passed to render_template take precedence. Keep a475 # copy to re-apply after all context functions.476 orig_ctx = context.copy()477478 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())482483 context.update(orig_ctx)484485 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.489490 .. versionadded:: 0.11491 """492 rv = {"app": self, "g": g}493 for processor in self.shell_context_processors:494 rv.update(processor())495 return rv496497 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.506507 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.510511 If the :attr:`debug` flag is set the server will automatically reload512 for code changes and show a debugger in case an exception happened.513514 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.518519 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.522523 .. admonition:: Keep in Mind524525 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.532533 :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.547548 .. versionchanged:: 1.0549 If installed, python-dotenv will be used to load environment550 variables from :file:`.env` and :file:`.flaskenv` files.551552 The :envvar:`FLASK_DEBUG` environment variable will override :attr:`debug`.553554 Threaded mode is enabled by default.555556 .. 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 )571572 return573574 if get_load_dotenv(load_dotenv):575 cli.load_dotenv()576577 # if set, env var overrides existing value578 if "FLASK_DEBUG" in os.environ:579 self.debug = get_debug_flag()580581 # debug passed to method overrides all other sources582 if debug is not None:583 self.debug = bool(debug)584585 server_name = self.config.get("SERVER_NAME")586 sn_host = sn_port = None587588 if server_name:589 sn_host, _, sn_port = server_name.partition(":")590591 if not host:592 if sn_host:593 host = sn_host594 else:595 host = "127.0.0.1"596597 if port or port == 0:598 port = int(port)599 elif sn_port:600 port = int(sn_port)601 else:602 port = 5000603604 options.setdefault("use_reloader", self.debug)605 options.setdefault("use_debugger", self.debug)606 options.setdefault("threaded", True)607608 cli.show_server_banner(self.debug, self.name)609610 from werkzeug.serving import run_simple611612 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 = False619620 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`.623624 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::631632 app.testing = True633 client = app.test_client()634635 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::638639 with app.test_client() as c:640 rv = c.get('/?vodka=42')641 assert request.args['vodka'] == '42'642643 Additionally, you may pass optional keyword arguments that will then644 be passed to the application's :attr:`test_client_class` constructor.645 For example::646647 from flask.testing import FlaskClient648649 class CustomClient(FlaskClient):650 def __init__(self, *args, **kwargs):651 self._authentication = kwargs.pop("authentication")652 super(CustomClient,self).__init__( *args, **kwargs)653654 app.test_client_class = CustomClient655 client = app.test_client(authentication='Basic ....')656657 See :class:`~flask.testing.FlaskClient` for more information.658659 .. versionchanged:: 0.4660 added support for ``with`` block usage for the client.661662 .. 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.666667 .. 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 )677678 def test_cli_runner(self, **kwargs: t.Any) -> FlaskCliRunner:679 """Create a CLI runner for testing CLI commands.680 See :ref:`testing-cli`.681682 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.685686 .. versionadded:: 1.0687 """688 cls = self.test_cli_runner_class689690 if cls is None:691 from .testing import FlaskCliRunner as cls692693 return cls(self, **kwargs) # type: ignore694695 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.701702 .. versionchanged:: 1.0.3703 ``RoutingException``, used internally for actions such as704 slash redirects during routing, is not passed to error705 handlers.706707 .. 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``.711712 .. 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 e718719 # 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 e724725 handler = self._find_error_handler(e, request.blueprints)726 if handler is None:727 return e728 return self.ensure_sync(handler)(e)729730 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.739740 .. 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.744745 .. versionadded:: 0.7746 """747 if isinstance(e, BadRequestKeyError) and (748 self.debug or self.config["TRAP_BAD_REQUEST_ERRORS"]749 ):750 e.show_exception = True751752 if isinstance(e, HTTPException) and not self.trap_http_exception(e):753 return self.handle_http_exception(e)754755 handler = self._find_error_handler(e, request.blueprints)756757 if handler is None:758 raise759760 return self.ensure_sync(handler)(e)761762 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``.766767 Always sends the :data:`got_request_exception` signal.768769 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.773774 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``.778779 .. versionchanged:: 1.1.0780 Always passes the ``InternalServerError`` instance to the781 handler, setting ``original_exception`` to the unhandled782 error.783784 .. versionchanged:: 1.1.0785 ``after_request`` functions and other finalization is done786 even for the default 500 response when there is no handler.787788 .. 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"]793794 if propagate is None:795 propagate = self.testing or self.debug796797 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 raise802803 raise e804805 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)809810 if handler is not None:811 server_error = self.ensure_sync(handler)(server_error)812813 return self.finalize_request(server_error, from_error_handler=True)814815 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`.823824 .. versionadded:: 0.8825 """826 self.logger.error(827 f"Exception on {request.path} [{request.method}]", exc_info=exc_info828 )829830 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`.835836 .. 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)854855 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.859860 .. versionadded:: 0.7861 """862 self._got_first_request = True863864 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)872873 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.882883 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.887888 :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 response903904 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.908909 .. 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 rv916917 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.921922 Override this method to change how the app runs async views.923924 .. versionadded:: 2.0925 """926 if iscoroutinefunction(func):927 return self.async_to_sync(func)928929 return func930931 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.935936 .. code-block:: python937938 result = app.async_to_sync(func)(*args, **kwargs)939940 Override this method to change how the app converts async code941 to be synchronously callable.942943 .. 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 None951952 return asgiref_async_to_sync(func)953954 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.965966 This is called by :func:`flask.url_for`, and can be called967 directly as well.968969 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.974975 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.982983 Functions can be decorated with :meth:`url_defaults` to modify984 keyword arguments before the URL is built.985986 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.990991 :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``.10061007 .. versionadded:: 2.21008 Moved from ``flask.url_for``, which calls this method.1009 """1010 req_ctx = _cv_request.get(None)10111012 if req_ctx is not None:1013 url_adapter = req_ctx.url_adapter1014 blueprint_name = req_ctx.request.blueprint10151016 # 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:]10231024 # 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)10301031 # 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)10381039 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 )10461047 # When outside a request, generate a URL with scheme and1048 # domain by default.1049 if _external is None:1050 _external = True10511052 # 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.")10561057 self.inject_url_defaults(endpoint, values)10581059 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)10721073 if _anchor is not None:1074 _anchor = _url_quote(_anchor, safe="%!#$&'()*+,/:;=?@")1075 rv = f"{rv}#{_anchor}"10761077 return rv10781079 def make_response(self, rv: ft.ResponseReturnValue) -> Response:1080 """Convert the return value from a view function to an instance of1081 :attr:`response_class`.10821083 :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``:10871088 ``str``1089 A response object is created with the string encoded to UTF-81090 as the body.10911092 ``bytes``1093 A response object is created with the bytes as the body.10941095 ``dict``1096 A dictionary that will be jsonify'd before being returned.10971098 ``list``1099 A list that will be jsonify'd before being returned.11001101 ``generator`` or ``iterator``1102 A generator that returns ``str`` or ``bytes`` to be1103 streamed as the response.11041105 ``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.11131114 :attr:`response_class`1115 The object is returned unchanged.11161117 other :class:`~werkzeug.wrappers.Response` class1118 The object is coerced to :attr:`response_class`.11191120 :func:`callable`1121 The function is called as a WSGI application. The result is1122 used to create a response object.11231124 .. versionchanged:: 2.21125 A generator will be converted to a streaming response.1126 A list will be converted to a JSON response.11271128 .. versionchanged:: 1.11129 A dict will be converted to a JSON response.11301131 .. versionchanged:: 0.91132 Previously a tuple was interpreted as the arguments for the1133 response object.1134 """11351136 status = headers = None11371138 # unpack tuple returns1139 if isinstance(rv, tuple):1140 len_rv = len(rv)11411142 # 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 )11581159 # 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 )11661167 # 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 )12041205 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 = status12121213 # extend existing headers with provided headers1214 if headers:1215 rv.headers.update(headers) # type: ignore[arg-type]12161217 return rv12181219 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.12241225 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))12301231 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)12351236 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)()12401241 if rv is not None:1242 return rv12431244 return None12451246 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.12501251 .. versionchanged:: 0.51252 As of Flask 0.5 the functions registered for after request1253 execution are called in reverse order of registration.12541255 :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]12601261 for func in ctx._after_request_functions:1262 response = self.ensure_sync(func)(response)12631264 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)12681269 if not self.session_interface.is_null_session(ctx.session):1270 self.session_interface.save_session(self, ctx.session, response)12711272 return response12731274 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.12791280 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.12841285 This is called by1286 :meth:`RequestContext.pop() <flask.ctx.RequestContext.pop>`,1287 which may be delayed during testing to maintain access to1288 resources.12891290 :param exc: An unhandled exception raised while dispatching the1291 request. Detected from the current exception information if1292 not passed. Passed to each teardown function.12931294 .. versionchanged:: 0.91295 Added the ``exc`` argument.1296 """1297 if exc is _sentinel:1298 exc = sys.exc_info()[1]12991300 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)13041305 request_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)13061307 def do_teardown_appcontext(1308 self, exc: BaseException | None = _sentinel # type: ignore1309 ) -> None:1310 """Called right before the application context is popped.13111312 When handling a request, the application context is popped1313 after the request context. See :meth:`do_teardown_request`.13141315 This calls all functions decorated with1316 :meth:`teardown_appcontext`. Then the1317 :data:`appcontext_tearing_down` signal is sent.13181319 This is called by1320 :meth:`AppContext.pop() <flask.ctx.AppContext.pop>`.13211322 .. versionadded:: 0.91323 """1324 if exc is _sentinel:1325 exc = sys.exc_info()[1]13261327 for func in reversed(self.teardown_appcontext_funcs):1328 self.ensure_sync(func)(exc)13291330 appcontext_tearing_down.send(self, _async_wrapper=self.ensure_sync, exc=exc)13311332 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.13361337 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.13411342 ::13431344 with app.app_context():1345 init_db()13461347 See :doc:`/appcontext`.13481349 .. versionadded:: 0.91350 """1351 return AppContext(self)13521353 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.13571358 See :doc:`/reqcontext`.13591360 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.13641365 :param environ: a WSGI environment1366 """1367 return RequestContext(self, environ)13681369 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.13741375 See :doc:`/reqcontext`.13761377 Use a ``with`` block to push the context, which will make1378 :data:`request` point at the request for the created1379 environment. ::13801381 with app.test_request_context(...):1382 generate_report()13831384 When using the shell, it may be easier to push and pop the1385 context manually to avoid indentation. ::13861387 ctx = app.test_request_context(...)1388 ctx.push()1389 ...1390 ctx.pop()13911392 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.13961397 :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 EnvironBuilder14171418 builder = EnvironBuilder(self, *args, **kwargs)14191420 try:1421 return self.request_context(builder.get_environ())1422 finally:1423 builder.close()14241425 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::14291430 app = MyMiddleware(app)14311432 It's a better idea to do this instead::14331434 app.wsgi_app = MyMiddleware(app.wsgi_app)14351436 Then you still have the original application object around and1437 can continue to call methods on it.14381439 .. 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`.14441445 :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())14671468 if error is not None and self.should_ignore_error(error):1469 error = None14701471 ctx.pop(error)14721473 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
1from __future__ import annotations23import os4import typing as t5from datetime import timedelta67from .globals import current_app8from .helpers import send_from_directory9from .sansio.blueprints import Blueprint as SansioBlueprint10from .sansio.blueprints import BlueprintSetupState as BlueprintSetupState # noqa1112if t.TYPE_CHECKING: # pragma: no cover13 from .wrappers import Response141516class 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.2021 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.2526 Note this is a duplicate of the same method in the Flask27 class.2829 .. versionchanged:: 2.030 The default configuration is ``None`` instead of 12 hours.3132 .. versionadded:: 0.933 """34 value = current_app.config["SEND_FILE_MAX_AGE_DEFAULT"]3536 if value is None:37 return None3839 if isinstance(value, timedelta):40 return int(value.total_seconds())4142 return value4344 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.4950 Note this is a duplicate of the same method in the Flask51 class.5253 .. versionadded:: 0.55455 """56 if not self.has_static_folder:57 raise RuntimeError("'static_folder' must be set to serve static_files.")5859 # 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 )6566 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.6970 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:7374 .. code-block:: python7576 with app.open_resource("schema.sql") as f:77 conn.executescript(f.read())7879 :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".8384 Note this is a duplicate of the same method in the Flask85 class.8687 """88 if mode not in {"r", "rt", "rb"}:89 raise ValueError("Resources can only be opened for reading.")9091 return open(os.path.join(self.root_path, resource), mode)
modified:src/flask/debughelpers.py+3 added-3 removed
1from __future__ import annotations23import typing as t45from .app import Flask5from .blueprints import Blueprint6from .globals import request_ctx7from .sansio.app import App8910class UnexpectedUnicodeError(AssertionError, UnicodeError):11 """Raised in places where we want some better error reporting for
100 unmodified lines
112 continue113 yield f"{key}: {value!r}"114115116def explain_template_loading_attempts(app: Flask, template, attempts) -> None:116def 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.blueprint123124 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 lines
modified:src/flask/logging.py+2 added-2 removed
7 unmodified lines
89from .globals import request1011if t.TYPE_CHECKING: # pragma: no cover12 from .app import Flask12 from .sansio.app import App131415@LocalProxy16def wsgi_errors_stream() -> t.TextIO:
34 unmodified lines
51 logging.Formatter("[%(asctime)s] %(levelname)s in %(module)s: %(message)s")52)535455def create_logger(app: Flask) -> logging.Logger:55def create_logger(app: App) -> logging.Logger:56 """Get the Flask app's logger and configure it if needed.5758 The logger name will be the same as59 :attr:`app.import_name <flask.Flask.name>`.
17 unmodified lines
modified:src/flask/templating.py+4 added-3 removed
15 unmodified lines
16from .signals import template_rendered1718if t.TYPE_CHECKING: # pragma: no cover19 from .app import Flask20 from .sansio.app import App20 from .scaffold import Scaffold21 from .sansio.scaffold import Scaffold222324def _default_template_ctx_processor() -> dict[str, t.Any]:25 """Default template context processor. Injects `request`,
15 unmodified lines
41 knowledge of how Flask's blueprint works so that it can prepend the42 name of the blueprint to referenced templates if necessary.43 """4444 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 = app
3 unmodified lines
53 """A loader that looks for templates in the application and all54 the blueprint folders.55 """5656 def __init__(self, app: Flask) -> None:57 def __init__(self, app: App) -> None:58 self.app = app5960 def get_source( # type: ignore61 self, environment: Environment, template: str
160 unmodified lines