Skip to content
Myr

Merge branch '2.1.x'

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parents 9e2e1de, c7f2ab8 · Browse files · 11 files+202 added−63 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

11 files+202 added−63 removed

  • tests:+114 added−15 removed
  • other:+88 added−48 removed

11 files+202 added−63 removed

modified:docs/testing.rst+4 added-4 removed
90 unmodified lines
91The ``client`` has methods that match the common HTTP request methods,92such as ``client.get()`` and ``client.post()``. They take many arguments93for building the request; you can find the full documentation in94:class:`~werkzeug.test.EnvironBuilder`. Typically you'll use ``path``,95``query``, ``headers``, and ``data`` or ``json``.95``query_string``, ``headers``, and ``data`` or ``json``.9697To make a request, call the method the request should use with the path98to the route to test. A :class:`~werkzeug.test.TestResponse` is returned99to examine the response data. It has all the usual properties of a
7 unmodified lines
107 response = client.get("/posts")108 assert b"<h2>Hello, World!</h2>" in response.data109110111Pass a dict ``query={"key": "value", ...}`` to set arguments in the112query string (after the ``?`` in the URL). Pass a dict ``headers={}``113to set request headers.111Pass a dict ``query_string={"key": "value", ...}`` to set arguments in112the query string (after the ``?`` in the URL). Pass a dict113``headers={}`` to set request headers.114115To send a request body in a POST or PUT request, pass a value to116``data``. If raw bytes are passed, that exact body is used. Usually,117you'll pass a dict to set form data.
202 unmodified lines
modified:src/flask/app.py+2 added-2 removed
1074 unmodified lines
1075 def add_url_rule(1076 self,1077 rule: str,1078 endpoint: t.Optional[str] = None,1079 view_func: t.Optional[t.Callable] = None,1079 view_func: t.Optional[ft.ViewCallable] = None,1080 provide_automatic_options: t.Optional[bool] = None,1081 **options: t.Any,1082 ) -> None:1083 if endpoint is None:
777 unmodified lines
1861 elif len_rv == 2:1862 if isinstance(rv[1], (Headers, dict, tuple, list)):1863 rv, headers = rv1864 else:1865 rv, status = rv # type: ignore[misc]1865 rv, status = rv # type: ignore[assignment,misc]1866 # other sized tuples are not allowed1867 else:1868 raise TypeError(1869 "The view function did not return a valid response tuple."
414 unmodified lines
modified:src/flask/blueprints.py+5 added-3 removed
390 unmodified lines
391 def add_url_rule(392 self,393 rule: str,394 endpoint: t.Optional[str] = None,395 view_func: t.Optional[t.Callable] = None,395 view_func: t.Optional[ft.ViewCallable] = None,396 provide_automatic_options: t.Optional[bool] = None,397 **options: t.Any,398 ) -> None:399 """Like :meth:`Flask.add_url_rule` but for a blueprint. The endpoint for
179 unmodified lines
579 )580 return f581582 @setupmethod583 def app_errorhandler(self, code: t.Union[t.Type[Exception], int]) -> t.Callable:583 def app_errorhandler(584 self, code: t.Union[t.Type[Exception], int]585 ) -> t.Callable[[ft.ErrorHandlerDecorator], ft.ErrorHandlerDecorator]:586 """Like :meth:`Flask.errorhandler` but for a blueprint. This587 handler is used for all requests, even if outside of the blueprint.588 """589588 def decorator(f: ft.ErrorHandlerCallable) -> ft.ErrorHandlerCallable:590 def decorator(f: ft.ErrorHandlerDecorator) -> ft.ErrorHandlerDecorator:591 self.record_once(lambda s: s.app.errorhandler(code)(f))592 return f593594 return decorator
18 unmodified lines
modified:src/flask/scaffold.py+61 added-24 removed
1import importlib.util2import os3import pathlib4import pkgutil5import sys6import typing as t7from collections import defaultdict
103 unmodified lines
111 #: directly and its format may change at any time.112 self.view_functions: t.Dict[str, t.Callable] = {}113114 #: A data structure of registered error handlers, in the format114 #: ``{scope: {code: {class: handler}}}```. The ``scope`` key is115 #: ``{scope: {code: {class: handler}}}``. The ``scope`` key is116 #: the name of a blueprint the handlers are active for, or117 #: ``None`` for all requests. The ``code`` key is the HTTP118 #: status code for ``HTTPException``, or ``None`` for119 #: other exceptions. The innermost dictionary maps exception
231 unmodified lines
351 self,352 method: str,353 rule: str,354 options: dict,354 ) -> t.Callable[[F], F]:355 ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:356 if "methods" in options:357 raise TypeError("Use the 'route' decorator to use the 'methods' argument.")358359 return self.route(rule, methods=[method], **options)360361 @setupmethod361 def get(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:362 def get(363 self, rule: str, **options: t.Any364 ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:365 """Shortcut for :meth:`route` with ``methods=["GET"]``.366367 .. versionadded:: 2.0368 """369 return self._method_route("GET", rule, options)370371 @setupmethod369 def post(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:372 def post(373 self, rule: str, **options: t.Any374 ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:375 """Shortcut for :meth:`route` with ``methods=["POST"]``.376377 .. versionadded:: 2.0378 """379 return self._method_route("POST", rule, options)380381 @setupmethod377 def put(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:382 def put(383 self, rule: str, **options: t.Any384 ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:385 """Shortcut for :meth:`route` with ``methods=["PUT"]``.386387 .. versionadded:: 2.0388 """389 return self._method_route("PUT", rule, options)390391 @setupmethod385 def delete(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:392 def delete(393 self, rule: str, **options: t.Any394 ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:395 """Shortcut for :meth:`route` with ``methods=["DELETE"]``.396397 .. versionadded:: 2.0398 """399 return self._method_route("DELETE", rule, options)400401 @setupmethod393 def patch(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:402 def patch(403 self, rule: str, **options: t.Any404 ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:405 """Shortcut for :meth:`route` with ``methods=["PATCH"]``.406407 .. versionadded:: 2.0408 """409 return self._method_route("PATCH", rule, options)410411 @setupmethod401 def route(self, rule: str, **options: t.Any) -> t.Callable[[F], F]:412 def route(413 self, rule: str, **options: t.Any414 ) -> t.Callable[[ft.RouteDecorator], ft.RouteDecorator]:415 """Decorate a view function to register it with the given URL416 rule and options. Calls :meth:`add_url_rule`, which has more417 details about the implementation.418
15 unmodified lines
434 :param options: Extra options passed to the435 :class:`~werkzeug.routing.Rule` object.436 """437425 def decorator(f: F) -> F:438 def decorator(f: ft.RouteDecorator) -> ft.RouteDecorator:439 endpoint = options.pop("endpoint", None)440 self.add_url_rule(rule, endpoint, f, **options)441 return f442
3 unmodified lines
446 def add_url_rule(447 self,448 rule: str,449 endpoint: t.Optional[str] = None,437 view_func: t.Optional[t.Callable] = None,450 view_func: t.Optional[ft.ViewCallable] = None,451 provide_automatic_options: t.Optional[bool] = None,452 **options: t.Any,453 ) -> None:454 """Register a rule for routing incoming requests and building
194 unmodified lines
649650 @setupmethod651 def errorhandler(652 self, code_or_exception: t.Union[t.Type[Exception], int]640 ) -> t.Callable[[ft.ErrorHandlerCallable], ft.ErrorHandlerCallable]:653 ) -> t.Callable[[ft.ErrorHandlerDecorator], ft.ErrorHandlerDecorator]:654 """Register a function to handle errors by code or exception class.655656 A decorator that is used to register a function given an657 error code. Example::
21 unmodified lines
679 :param code_or_exception: the code as integer for the handler, or680 an arbitrary exception681 """682670 def decorator(f: ft.ErrorHandlerCallable) -> ft.ErrorHandlerCallable:683 def decorator(f: ft.ErrorHandlerDecorator) -> ft.ErrorHandlerDecorator:684 self.register_error_handler(code_or_exception, f)685 return f686687 return decorator
90 unmodified lines
778 f" import hooks."779 )780781782def _path_is_relative_to(path: pathlib.PurePath, base: str) -> bool:783 # Path.is_relative_to doesn't exist until Python 3.9784 try:785 path.relative_to(base)786 return True787 except ValueError:788 return False789790769def _find_package_path(root_mod_name):791def _find_package_path(import_name):792 """Find the path that contains the package or module."""793 root_mod_name, _, _ = import_name.partition(".")794795 try:772 spec = importlib.util.find_spec(root_mod_name)796 root_spec = importlib.util.find_spec(root_mod_name)797774 if spec is None:798 if root_spec is None:799 raise ValueError("not found")800 # ImportError: the machinery told us it does not exist801 # ValueError:802 # - the module name was invalid803 # - the module name is __main__780 # - *we* raised `ValueError` due to `spec` being `None`804 # - *we* raised `ValueError` due to `root_spec` being `None`805 except (ImportError, ValueError):806 pass # handled below807 else:808 # namespace package785 if spec.origin in {"namespace", None}:786 return os.path.dirname(next(iter(spec.submodule_search_locations)))809 if root_spec.origin in {"namespace", None}:810 package_spec = importlib.util.find_spec(import_name)811 if package_spec is not None and package_spec.submodule_search_locations:812 # Pick the path in the namespace that contains the submodule.813 package_path = pathlib.Path(814 os.path.commonpath(package_spec.submodule_search_locations)815 )816 search_locations = (817 location818 for location in root_spec.submodule_search_locations819 if _path_is_relative_to(package_path, location)820 )821 else:822 # Pick the first path.823 search_locations = iter(root_spec.submodule_search_locations)824 return os.path.dirname(next(search_locations))825 # a package (with __init__.py)788 elif spec.submodule_search_locations:789 return os.path.dirname(os.path.dirname(spec.origin))826 elif root_spec.submodule_search_locations:827 return os.path.dirname(os.path.dirname(root_spec.origin))828 # just a normal module829 else:792 return os.path.dirname(spec.origin)830 return os.path.dirname(root_spec.origin)831832 # we were unable to find the `package_path` using PEP 451 loaders833 loader = pkgutil.get_loader(root_mod_name)834
33 unmodified lines
868 The path is the entry in :attr:`sys.path` that contains the package869 for import. If the package is not installed, it's assumed that the870 package was imported from the current working directory.871 """834 root_mod_name, _, _ = import_name.partition(".")835 package_path = _find_package_path(root_mod_name)872 package_path = _find_package_path(import_name)873 py_prefix = os.path.abspath(sys.prefix)874875 # installed to the system839 if package_path.startswith(py_prefix):876 if _path_is_relative_to(pathlib.PurePath(package_path), py_prefix):877 return py_prefix, package_path878879 site_parent, site_folder = os.path.split(package_path)880
17 unmodified lines
modified:src/flask/typing.py+12 added-14 removed
1import typing as t233if t.TYPE_CHECKING: # pragma: no cover4 from _typeshed.wsgi import WSGIApplication # noqa: F4015 from werkzeug.datastructures import Headers # noqa: F4016 from werkzeug.wrappers import Response # noqa: F40178# The possible types that are directly convertible or are a Response object.10ResponseValue = t.Union[11 "Response",12 str,13 bytes,14 t.Dict[str, t.Any], # any jsonify-able dict15 t.Iterator[str],16 t.Iterator[bytes],17]18StatusCode = int9ResponseValue = t.Union["Response", str, bytes, t.Dict[str, t.Any]]1011# the possible types for an individual HTTP header21HeaderName = str12# This should be a Union, but mypy doesn't pass unless it's a TypeVar.13HeaderValue = t.Union[str, t.List[str], t.Tuple[str, ...]]1415# the possible types for HTTP headers16HeadersValue = t.Union[26 "Headers", t.Dict[HeaderName, HeaderValue], t.List[t.Tuple[HeaderName, HeaderValue]]17 "Headers",18 t.Mapping[str, HeaderValue],19 t.Sequence[t.Tuple[str, HeaderValue]],20]2122# The possible types returned by a route function.23ResponseReturnValue = t.Union[24 ResponseValue,25 t.Tuple[ResponseValue, HeadersValue],33 t.Tuple[ResponseValue, StatusCode],34 t.Tuple[ResponseValue, StatusCode, HeadersValue],26 t.Tuple[ResponseValue, int],27 t.Tuple[ResponseValue, int, HeadersValue],28 "WSGIApplication",29]3031# Allow any subclass of werkzeug.Response, such as the one from Flask,
11 unmodified lines
43TemplateGlobalCallable = t.Callable[..., t.Any]44TemplateTestCallable = t.Callable[..., bool]45URLDefaultCallable = t.Callable[[str, dict], None]46URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]4748# This should take Exception, but that either breaks typing the argument49# with a specific exception, or decorating multiple times with different50# exceptions (and using a union type on the argument).51# https://github.com/pallets/flask/issues/409552# https://github.com/pallets/flask/issues/429553# https://github.com/pallets/flask/issues/429754ErrorHandlerCallable = t.Callable[[t.Any], ResponseReturnValue]55ErrorHandlerDecorator = t.TypeVar("ErrorHandlerDecorator", bound=ErrorHandlerCallable)5657ViewCallable = t.Callable[..., ResponseReturnValue]58RouteDecorator = t.TypeVar("RouteDecorator", bound=ViewCallable)
added:tests/typing/typing_error_handler.py+33 added
1from __future__ import annotations23from http import HTTPStatus45from werkzeug.exceptions import BadRequest6from werkzeug.exceptions import NotFound78from flask import Flask910app = Flask(__name__)111213@app.errorhandler(400)14@app.errorhandler(HTTPStatus.BAD_REQUEST)15@app.errorhandler(BadRequest)16def handle_400(e: BadRequest) -> str:17 return ""181920@app.errorhandler(ValueError)21def handle_custom(e: ValueError) -> str:22 return ""232425@app.errorhandler(ValueError)26def handle_accept_base(e: Exception) -> str:27 return ""282930@app.errorhandler(BadRequest)31@app.errorhandler(404)32def handle_multiple(e: BadRequest | NotFound) -> str:33 return ""
added:tests/typing/typing_route.py+62 added
1from __future__ import annotations23from http import HTTPStatus45from flask import Flask6from flask import jsonify7from flask.templating import render_template8from flask.views import View9from flask.wrappers import Response1011app = Flask(__name__)121314@app.route("/str")15def hello_str() -> str:16 return "<p>Hello, World!</p>"171819@app.route("/bytes")20def hello_bytes() -> bytes:21 return b"<p>Hello, World!</p>"222324@app.route("/json")25def hello_json() -> Response:26 return jsonify({"response": "Hello, World!"})272829@app.route("/status")30@app.route("/status/<int:code>")31def tuple_status(code: int = 200) -> tuple[str, int]:32 return "hello", code333435@app.route("/status-enum")36def tuple_status_enum() -> tuple[str, int]:37 return "hello", HTTPStatus.OK383940@app.route("/headers")41def tuple_headers() -> tuple[str, dict[str, str]]:42 return "Hello, World!", {"Content-Type": "text/plain"}434445@app.route("/template")46@app.route("/template/<name>")47def return_template(name: str | None = None) -> str:48 return render_template("index.html", name=name)495051class RenderTemplateView(View):52 def __init__(self: RenderTemplateView, template_name: str) -> None:53 self.template_name = template_name5455 def dispatch_request(self: RenderTemplateView) -> str:56 return render_template(self.template_name)575859app.add_url_rule(60 "/about",61 view_func=RenderTemplateView.as_view("about_page", template_name="about.html"),62)
modified:tests/test_instance_config.py+19 added-15 removed
1import os1import sys23import pytest4
8 unmodified lines
13 app = flask.Flask(__name__, instance_path=str(modules_tmpdir))14 assert app.instance_path == str(modules_tmpdir)151618@pytest.mark.xfail(reason="weird interaction with tox")19def test_main_module_paths(modules_tmpdir, purge_module):20 app = modules_tmpdir.join("main_app.py")21 app.write('import flask\n\napp = flask.Flask("__main__")')22 purge_module("main_app")2324 from main_app import app2526 here = os.path.abspath(os.getcwd())27 assert app.instance_path == os.path.join(here, "instance")282930@pytest.mark.xfail(reason="weird interaction with tox")17def test_uninstalled_module_paths(modules_tmpdir, purge_module):18 app = modules_tmpdir.join("config_module_app.py").write(19 "import os\n"20 "import flask\n"
6 unmodified lines
2728 assert app.instance_path == str(modules_tmpdir.join("instance"))293045@pytest.mark.xfail(reason="weird interaction with tox")31def test_uninstalled_package_paths(modules_tmpdir, purge_module):32 app = modules_tmpdir.mkdir("config_package_app")33 init = app.join("__init__.py")34 init.write(
8 unmodified lines
4344 assert app.instance_path == str(modules_tmpdir.join("instance"))454647def test_uninstalled_namespace_paths(tmpdir, monkeypatch, purge_module):48 def create_namespace(package):49 project = tmpdir.join(f"project-{package}")50 monkeypatch.syspath_prepend(str(project))51 project.join("namespace").join(package).join("__init__.py").write(52 "import flask\napp = flask.Flask(__name__)\n", ensure=True53 )54 return project5556 _ = create_namespace("package1")57 project2 = create_namespace("package2")58 purge_module("namespace.package2")59 purge_module("namespace")6061 from namespace.package2 import app6263 assert app.instance_path == str(project2.join("instance"))646566def test_installed_module_paths(67 modules_tmpdir, modules_tmpdir_prefix, purge_module, site_packages, limit_loader68):69 site_packages.join("site_app.py").write(
56 unmodified lines
modified:CHANGES.rst+2 added
28 unmodified lines
2930- Inline some optional imports that are only used for certain CLI31 commands. :pr:`4606`32- Relax type annotation for ``after_request`` functions. :issue:`4600`33- ``instance_path`` for namespace packages uses the path closest to34 the imported submodule. :issue:`4600`353637Version 2.1.238-------------
1280 unmodified lines
modified:setup.cfg+1 added-1 removed
85 unmodified lines
86 # __init__ exports names87 src/flask/__init__.py: F4018889[mypy]90files = src/flask90files = src/flask, tests/typing91python_version = 3.792show_error_codes = True93allow_redefinition = True94disallow_subclassing_any = True
27 unmodified lines
modified:tox.ini+1 added
7 unmodified lines
8 docs9skip_missing_interpreters = true1011[testenv]12envtmpdir = {toxworkdir}/tmp/{envname}13deps =14 -r requirements/tests.txt15 min: -r requirements/tests-pallets-min.txt16 dev: -r requirements/tests-pallets-dev.txt
18 unmodified lines