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
Provenance
- Commit
7a2d5fb- Tree
2a88ae2- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
9e2e1de- Parent 2
c7f2ab8
11 files changed+202 added−63 removed
modified:docs/testing.rst+4 added-4 removed
90 unmodified lines91 The ``client`` has methods that match the common HTTP request methods,92 such as ``client.get()`` and ``client.post()``. They take many arguments93 for 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``.96 97 To make a request, call the method the request should use with the path98 to the route to test. A :class:`~werkzeug.test.TestResponse` is returned99 to examine the response data. It has all the usual properties of a7 unmodified lines107 response = client.get("/posts")108 assert b"<h2>Hello, World!</h2>" in response.data109 110 111-Pass a dict ``query={"key": "value", ...}`` to set arguments in the112-query string (after the ``?`` in the URL). Pass a dict ``headers={}``113-to set request headers.111+Pass a dict ``query_string={"key": "value", ...}`` to set arguments in112+the query string (after the ``?`` in the URL). Pass a dict113+``headers={}`` to set request headers.114 115 To 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,117 you'll pass a dict to set form data.202 unmodified linesmodified:src/flask/app.py+2 added-2 removed
1074 unmodified lines1075 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 lines1861 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 linesmodified:src/flask/blueprints.py+5 added-3 removed
390 unmodified lines391 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 for179 unmodified lines579 )580 return f581 582 @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 """589 588- 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 f593 594 return decorator18 unmodified linesmodified:src/flask/scaffold.py+61 added-24 removed
1 import importlib.util2 import os3+import pathlib4 import pkgutil5 import sys6 import typing as t7 from collections import defaultdict103 unmodified lines111 #: directly and its format may change at any time.112 self.view_functions: t.Dict[str, t.Callable] = {}113 114 #: 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 exception231 unmodified lines351 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.")358 359 return self.route(rule, methods=[method], **options)360 361 @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"]``.366 367 .. versionadded:: 2.0368 """369 return self._method_route("GET", rule, options)370 371 @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"]``.376 377 .. versionadded:: 2.0378 """379 return self._method_route("POST", rule, options)380 381 @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"]``.386 387 .. versionadded:: 2.0388 """389 return self._method_route("PUT", rule, options)390 391 @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"]``.396 397 .. versionadded:: 2.0398 """399 return self._method_route("DELETE", rule, options)400 401 @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"]``.406 407 .. versionadded:: 2.0408 """409 return self._method_route("PATCH", rule, options)410 411 @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 lines434 :param options: Extra options passed to the435 :class:`~werkzeug.routing.Rule` object.436 """437 425- 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 lines446 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 building194 unmodified lines649 650 @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.655 656 A decorator that is used to register a function given an657 error code. Example::21 unmodified lines679 :param code_or_exception: the code as integer for the handler, or680 an arbitrary exception681 """682 670- 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 f686 687 return decorator90 unmodified lines778 f" import hooks."779 )780 781 782+def _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 False789+790+769-def _find_package_path(root_mod_name):791+def _find_package_path(import_name):792 """Find the path that contains the package or module."""793+ root_mod_name, _, _ = import_name.partition(".")794+795 try:772- spec = importlib.util.find_spec(root_mod_name)796+ root_spec = importlib.util.find_spec(root_mod_name)797 774- 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)831 832 # we were unable to find the `package_path` using PEP 451 loaders833 loader = pkgutil.get_loader(root_mod_name)834 33 unmodified lines868 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)874 875 # 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_path878 879 site_parent, site_folder = os.path.split(package_path)880 17 unmodified linesmodified:src/flask/typing.py+12 added-14 removed
1 import typing as t2 3-3 if 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: F4017 8 # The possible types that are directly convertible or are a Response object.10-ResponseValue = 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-]18-StatusCode = int9+ResponseValue = t.Union["Response", str, bytes, t.Dict[str, t.Any]]10 11 # the possible types for an individual HTTP header21-HeaderName = str12+# This should be a Union, but mypy doesn't pass unless it's a TypeVar.13 HeaderValue = t.Union[str, t.List[str], t.Tuple[str, ...]]14 15 # the possible types for HTTP headers16 HeadersValue = 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 ]21 22 # The possible types returned by a route function.23 ResponseReturnValue = 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 ]30 31 # Allow any subclass of werkzeug.Response, such as the one from Flask,11 unmodified lines43 TemplateGlobalCallable = t.Callable[..., t.Any]44 TemplateTestCallable = t.Callable[..., bool]45 URLDefaultCallable = t.Callable[[str, dict], None]46 URLValuePreprocessorCallable = t.Callable[[t.Optional[str], t.Optional[dict]], None]47+48 # 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/429754 ErrorHandlerCallable = t.Callable[[t.Any], ResponseReturnValue]55+ErrorHandlerDecorator = t.TypeVar("ErrorHandlerDecorator", bound=ErrorHandlerCallable)56+57+ViewCallable = t.Callable[..., ResponseReturnValue]58+RouteDecorator = t.TypeVar("RouteDecorator", bound=ViewCallable)added:tests/typing/typing_error_handler.py+33 added
1+from __future__ import annotations2+3+from http import HTTPStatus4+5+from werkzeug.exceptions import BadRequest6+from werkzeug.exceptions import NotFound7+8+from flask import Flask9+10+app = Flask(__name__)11+12+13+@app.errorhandler(400)14+@app.errorhandler(HTTPStatus.BAD_REQUEST)15+@app.errorhandler(BadRequest)16+def handle_400(e: BadRequest) -> str:17+ return ""18+19+20+@app.errorhandler(ValueError)21+def handle_custom(e: ValueError) -> str:22+ return ""23+24+25+@app.errorhandler(ValueError)26+def handle_accept_base(e: Exception) -> str:27+ return ""28+29+30+@app.errorhandler(BadRequest)31+@app.errorhandler(404)32+def handle_multiple(e: BadRequest | NotFound) -> str:33+ return ""added:tests/typing/typing_route.py+62 added
1+from __future__ import annotations2+3+from http import HTTPStatus4+5+from flask import Flask6+from flask import jsonify7+from flask.templating import render_template8+from flask.views import View9+from flask.wrappers import Response10+11+app = Flask(__name__)12+13+14+@app.route("/str")15+def hello_str() -> str:16+ return "<p>Hello, World!</p>"17+18+19+@app.route("/bytes")20+def hello_bytes() -> bytes:21+ return b"<p>Hello, World!</p>"22+23+24+@app.route("/json")25+def hello_json() -> Response:26+ return jsonify({"response": "Hello, World!"})27+28+29+@app.route("/status")30+@app.route("/status/<int:code>")31+def tuple_status(code: int = 200) -> tuple[str, int]:32+ return "hello", code33+34+35+@app.route("/status-enum")36+def tuple_status_enum() -> tuple[str, int]:37+ return "hello", HTTPStatus.OK38+39+40+@app.route("/headers")41+def tuple_headers() -> tuple[str, dict[str, str]]:42+ return "Hello, World!", {"Content-Type": "text/plain"}43+44+45+@app.route("/template")46+@app.route("/template/<name>")47+def return_template(name: str | None = None) -> str:48+ return render_template("index.html", name=name)49+50+51+class RenderTemplateView(View):52+ def __init__(self: RenderTemplateView, template_name: str) -> None:53+ self.template_name = template_name54+55+ def dispatch_request(self: RenderTemplateView) -> str:56+ return render_template(self.template_name)57+58+59+app.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
1-import os1 import sys2 3 import pytest4 8 unmodified lines13 app = flask.Flask(__name__, instance_path=str(modules_tmpdir))14 assert app.instance_path == str(modules_tmpdir)15 16 18-@pytest.mark.xfail(reason="weird interaction with tox")19-def 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")23-24- from main_app import app25-26- here = os.path.abspath(os.getcwd())27- assert app.instance_path == os.path.join(here, "instance")28-29-30-@pytest.mark.xfail(reason="weird interaction with tox")17 def 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 lines27 28 assert app.instance_path == str(modules_tmpdir.join("instance"))29 30 45-@pytest.mark.xfail(reason="weird interaction with tox")31 def 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 lines43 44 assert app.instance_path == str(modules_tmpdir.join("instance"))45 46 47+def 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 project55+56+ _ = create_namespace("package1")57+ project2 = create_namespace("package2")58+ purge_module("namespace.package2")59+ purge_module("namespace")60+61+ from namespace.package2 import app62+63+ assert app.instance_path == str(project2.join("instance"))64+65+66 def 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 linesmodified:CHANGES.rst+2 added
28 unmodified lines29 30 - 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`35 36 37 Version 2.1.238 -------------1280 unmodified linesmodified:setup.cfg+1 added-1 removed
85 unmodified lines86 # __init__ exports names87 src/flask/__init__.py: F40188 89 [mypy]90-files = src/flask90+files = src/flask, tests/typing91 python_version = 3.792 show_error_codes = True93 allow_redefinition = True94 disallow_subclassing_any = True27 unmodified linesmodified:tox.ini+1 added
7 unmodified lines8 docs9 skip_missing_interpreters = true10 11 [testenv]12+envtmpdir = {toxworkdir}/tmp/{envname}13 deps =14 -r requirements/tests.txt15 min: -r requirements/tests-pallets-min.txt16 dev: -r requirements/tests-pallets-dev.txt18 unmodified lines