From d3e4dd75e3620c1492682aeeca9734eaf25719dd Mon Sep 17 00:00:00 2001 From: "deepin-community-bot[bot]" <156989552+deepin-community-bot[bot]@users.noreply.github.com> Date: Mon, 6 Jan 2025 05:41:46 +0000 Subject: [PATCH] feat: update python-werkzeug to 3.1.3-2 --- .pre-commit-config.yaml | 6 +- CHANGES.rst | 125 ++++ debian/changelog | 33 + debian/control | 33 +- ...-Use-intersphix-with-Debian-packages.patch | 4 +- debian/patches/series | 1 - ...rve-any-existing-PYTHONPATH-in-tests.patch | 31 - debian/rules | 9 +- docs/conf.py | 2 +- docs/datastructures.rst | 53 +- docs/exceptions.rst | 2 + docs/installation.rst | 2 +- docs/quickstart.rst | 10 +- docs/request_data.rst | 15 +- docs/tutorial.rst | 4 +- pyproject.toml | 17 +- requirements/build.txt | 8 +- requirements/dev.txt | 98 ++- requirements/docs.txt | 43 +- requirements/tests.in | 4 +- requirements/tests.txt | 25 +- requirements/typing.txt | 27 +- src/werkzeug/__init__.py | 21 - src/werkzeug/_reloader.py | 29 +- src/werkzeug/datastructures/__init__.py | 34 +- src/werkzeug/datastructures/accept.py | 98 ++- src/werkzeug/datastructures/accept.pyi | 54 -- src/werkzeug/datastructures/auth.py | 3 +- src/werkzeug/datastructures/cache_control.py | 242 +++++-- src/werkzeug/datastructures/cache_control.pyi | 115 --- src/werkzeug/datastructures/csp.py | 82 ++- src/werkzeug/datastructures/csp.pyi | 169 ----- src/werkzeug/datastructures/etag.py | 49 +- src/werkzeug/datastructures/etag.pyi | 30 - src/werkzeug/datastructures/file_storage.py | 85 ++- src/werkzeug/datastructures/file_storage.pyi | 49 -- src/werkzeug/datastructures/headers.py | 419 +++++++---- src/werkzeug/datastructures/headers.pyi | 109 --- src/werkzeug/datastructures/mixins.py | 295 +++++--- src/werkzeug/datastructures/mixins.pyi | 97 --- src/werkzeug/datastructures/range.py | 122 ++-- src/werkzeug/datastructures/range.pyi | 57 -- src/werkzeug/datastructures/structures.py | 669 ++++++++++++------ src/werkzeug/datastructures/structures.pyi | 206 ------ src/werkzeug/debug/__init__.py | 19 +- src/werkzeug/debug/shared/debugger.js | 36 +- src/werkzeug/debug/tbtools.py | 17 +- src/werkzeug/exceptions.py | 15 +- src/werkzeug/formparser.py | 27 +- src/werkzeug/http.py | 85 ++- src/werkzeug/middleware/lint.py | 2 +- src/werkzeug/middleware/shared_data.py | 9 +- src/werkzeug/routing/rules.py | 45 +- src/werkzeug/sansio/http.py | 1 - src/werkzeug/sansio/multipart.py | 2 + src/werkzeug/sansio/request.py | 6 +- src/werkzeug/sansio/response.py | 9 + src/werkzeug/sansio/utils.py | 8 + src/werkzeug/security.py | 7 +- src/werkzeug/serving.py | 15 +- src/werkzeug/test.py | 6 +- src/werkzeug/utils.py | 2 +- src/werkzeug/wrappers/request.py | 7 +- tests/conftest.py | 247 +++++-- tests/live_apps/run.py | 5 + tests/middleware/test_http_proxy.py | 1 - tests/sansio/test_utils.py | 4 + tests/test_datastructures.py | 112 ++- tests/test_debug.py | 1 - tests/test_exceptions.py | 1 + tests/test_formparser.py | 22 +- tests/test_http.py | 43 +- tests/test_security.py | 19 +- tests/test_serving.py | 118 +-- tests/test_wrappers.py | 7 +- tox.ini | 29 +- 76 files changed, 2418 insertions(+), 2095 deletions(-) delete mode 100644 debian/patches/tests-Preserve-any-existing-PYTHONPATH-in-tests.patch delete mode 100644 src/werkzeug/datastructures/accept.pyi delete mode 100644 src/werkzeug/datastructures/cache_control.pyi delete mode 100644 src/werkzeug/datastructures/csp.pyi delete mode 100644 src/werkzeug/datastructures/etag.pyi delete mode 100644 src/werkzeug/datastructures/file_storage.pyi delete mode 100644 src/werkzeug/datastructures/headers.pyi delete mode 100644 src/werkzeug/datastructures/mixins.pyi delete mode 100644 src/werkzeug/datastructures/range.pyi delete mode 100644 src/werkzeug/datastructures/structures.pyi diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 8289161..6ad19aa 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,13 +1,11 @@ -ci: - autoupdate_schedule: monthly repos: - repo: https://github.com/astral-sh/ruff-pre-commit - rev: v0.3.5 + rev: v0.7.1 hooks: - id: ruff - id: ruff-format - repo: https://github.com/pre-commit/pre-commit-hooks - rev: v4.6.0 + rev: v5.0.0 hooks: - id: check-merge-conflict - id: debug-statements diff --git a/CHANGES.rst b/CHANGES.rst index f6158e7..de3f2b7 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,5 +1,129 @@ .. currentmodule:: werkzeug +Version 3.1.3 +------------- + +Released 2024-11-08 + +- Initial data passed to ``MultiDict`` and similar interfaces only accepts + ``list``, ``tuple``, or ``set`` when passing multiple values. It had been + changed to accept any ``Collection``, but this matched types that should be + treated as single values, such as ``bytes``. :issue:`2994` +- When the ``Host`` header is not set and ``Request.host`` falls back to the + WSGI ``SERVER_NAME`` value, if that value is an IPv6 address it is wrapped + in ``[]`` to match the ``Host`` header. :issue:`2993` + + +Version 3.1.2 +------------- + +Released 2024-11-04 + +- Improve type annotation for ``TypeConversionDict.get`` to allow the ``type`` + parameter to be a callable. :issue:`2988` +- ``Headers`` does not inherit from ``MutableMapping``, as it is does not + exactly match that interface. :issue:`2989` + + +Version 3.1.1 +------------- + +Released 2024-11-01 + +- Fix an issue that caused ``str(Request.headers)`` to always appear empty. + :issue:`2985` + + +Version 3.1.0 +------------- + +Released 2024-10-31 + +- Drop support for Python 3.8. :pr:`2966` +- Remove previously deprecated code. :pr:`2967` +- ``Request.max_form_memory_size`` defaults to 500kB instead of unlimited. + Non-file form fields over this size will cause a ``RequestEntityTooLarge`` + error. :issue:`2964` +- ``OrderedMultiDict`` and ``ImmutableOrderedMultiDict`` are deprecated. + Use ``MultiDict`` and ``ImmutableMultiDict`` instead. :issue:`2968` +- Behavior of properties on ``request.cache_control`` and + ``response.cache_control`` has been significantly adjusted. + + - Dict values are always ``str | None``. Setting properties will convert + the value to a string. Setting a property to ``False`` is equivalent to + setting it to ``None``. Getting typed properties will return ``None`` if + conversion raises ``ValueError``, rather than the string. :issue:`2980` + - ``max_age`` is ``None`` if present without a value, rather than ``-1``. + :issue:`2980` + - ``no_cache`` is a boolean for requests, it is ``True`` instead of + ``"*"`` when present. It remains a string for responses. :issue:`2980` + - ``max_stale`` is ``True`` if present without a value, rather + than ``"*"``. :issue:`2980` + - ``no_transform`` is a boolean. Previously it was mistakenly always + ``None``. :issue:`2881` + - ``min_fresh`` is ``None`` if present without a value, rather than + ``"*"``. :issue:`2881` + - ``private`` is ``True`` if present without a value, rather than ``"*"``. + :issue:`2980` + - Added the ``must_understand`` property. :issue:`2881` + - Added the ``stale_while_revalidate``, and ``stale_if_error`` + properties. :issue:`2948` + - Type annotations more accurately reflect the values. :issue:`2881` + +- Support Cookie CHIPS (Partitioned Cookies). :issue:`2797` +- Add 421 ``MisdirectedRequest`` HTTP exception. :issue:`2850` +- Increase default work factor for PBKDF2 to 1,000,000 iterations. + :issue:`2969` +- Inline annotations for ``datastructures``, removing stub files. + :issue:`2970` +- ``MultiDict.getlist`` catches ``TypeError`` in addition to ``ValueError`` + when doing type conversion. :issue:`2976` +- Implement ``|`` and ``|=`` operators for ``MultiDict``, ``Headers``, and + ``CallbackDict``, and disallow ``|=`` on immutable types. :issue:`2977` + + +Version 3.0.6 +------------- + +Released 2024-10-25 + +- Fix how ``max_form_memory_size`` is applied when parsing large non-file + fields. :ghsa:`q34m-jh98-gwm2` +- ``safe_join`` catches certain paths on Windows that were not caught by + ``ntpath.isabs`` on Python < 3.11. :ghsa:`f9vj-2wh5-fj8j` + + +Version 3.0.5 +------------- + +Released 2024-10-24 + +- The Watchdog reloader ignores file closed no write events. :issue:`2945` +- Logging works with client addresses containing an IPv6 scope :issue:`2952` +- Ignore invalid authorization parameters. :issue:`2955` +- Improve type annotation fore ``SharedDataMiddleware``. :issue:`2958` +- Compatibility with Python 3.13 when generating debugger pin and the current + UID does not have an associated name. :issue:`2957` + + +Version 3.0.4 +------------- + +Released 2024-08-21 + +- Restore behavior where parsing `multipart/x-www-form-urlencoded` data with + invalid UTF-8 bytes in the body results in no form data parsed rather than a + 413 error. :issue:`2930` +- Improve ``parse_options_header`` performance when parsing unterminated + quoted string values. :issue:`2904` +- Debugger pin auth is synchronized across threads/processes when tracking + failed entries. :issue:`2916` +- Dev server handles unexpected `SSLEOFError` due to issue in Python < 3.13. + :issue:`2926` +- Debugger pin auth works when the URL already contains a query string. + :issue:`2918` + + Version 3.0.3 ------------- @@ -17,6 +141,7 @@ Released 2024-05-05 URIs to be passed on without encoding. :issue:`2828` - Type annotation for ``Rule.endpoint`` and other uses of ``endpoint`` is ``Any``. :issue:`2836` +- Make reloader more robust when ``""`` is in ``sys.path``. :pr:`2823` Version 3.0.2 diff --git a/debian/changelog b/debian/changelog index d20a26c..2a289b8 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,3 +1,36 @@ +python-werkzeug (3.1.3-2) unstable; urgency=medium + + * Team upload + * Upload to unstable + Fixes CVE-2024-49767 + + -- Carsten Schoenert Mon, 25 Nov 2024 17:32:31 +0100 + +python-werkzeug (3.1.3-1) experimental; urgency=medium + + * Team upload + * [a3a30e6] d/control: Sort the binary packages alphabetical + * [f09c7a3] New upstream version 3.1.3 + Fixes CVE-2024-49767 + (Closes: #1086062) + * [8afd1df] Rebuild patch queue from patch-queue branch + Dropped patch (included upstream): + tests-Preserve-any-existing-PYTHONPATH-in-tests.patch + * [edf459d] d/rules: Add variable PYBUILD_TEST_ARGS + We need to ignore some tests at build time now. + * [1346e45] d/rules: Drop -D option from SPHINXOPTS + * [804f129] d/control: python3-werkzeug - Drop dep on jibjs-jquery + (Closes: #1065427) + + -- Carsten Schoenert Sun, 24 Nov 2024 08:50:18 +0100 + +python-werkzeug (3.0.4-1) unstable; urgency=medium + + * Team upload + * [85ea57f] New upstream version 3.0.4 + + -- Carsten Schoenert Thu, 29 Aug 2024 17:44:25 +0200 + python-werkzeug (3.0.3-1) unstable; urgency=medium * Team upload diff --git a/debian/control b/debian/control index 2efabf2..34b1a42 100644 --- a/debian/control +++ b/debian/control @@ -30,10 +30,24 @@ Vcs-Browser: https://salsa.debian.org/python-team/packages/python-werkzeug Testsuite: autopkgtest-pkg-python Rules-Requires-Root: no +Package: python-werkzeug-doc +Section: doc +Architecture: all +Depends: + ${misc:Depends}, + ${sphinxdoc:Depends}, +Multi-Arch: foreign +Description: Documentation for the werkzeug Python library (docs) + Werkzeug is a lightweight library for interfacing with WSGI. It features + request and response objects, an interactive debugging system and a powerful + URI dispatcher. Combine with your choice of third party libraries and + middleware to easily create a custom application framework. + . + This package provides the Sphinx generated documentation for Werkzeug. + Package: python3-werkzeug Architecture: all Depends: - libjs-jquery, ${misc:Depends}, ${python3:Depends}, Recommends: @@ -45,7 +59,7 @@ Suggests: python3-lxml, python3-pkg-resources, python3-watchdog, -Description: collection of utilities for WSGI applications (Python 3.x) +Description: Collection of utilities for WSGI applications (Python 3.x) The Web Server Gateway Interface (WSGI) is a standard interface between web server software and web applications written in Python. . @@ -55,18 +69,3 @@ Description: collection of utilities for WSGI applications (Python 3.x) middleware to easily create a custom application framework. . This package contains the Python 3.x module. - -Package: python-werkzeug-doc -Section: doc -Architecture: all -Depends: - ${misc:Depends}, - ${sphinxdoc:Depends}, -Multi-Arch: foreign -Description: documentation for the werkzeug Python library (docs) - Werkzeug is a lightweight library for interfacing with WSGI. It features - request and response objects, an interactive debugging system and a powerful - URI dispatcher. Combine with your choice of third party libraries and - middleware to easily create a custom application framework. - . - This package provides the Sphinx generated documentation for Werkzeug. diff --git a/debian/patches/docs-Use-intersphix-with-Debian-packages.patch b/debian/patches/docs-Use-intersphix-with-Debian-packages.patch index 88c245b..671030f 100644 --- a/debian/patches/docs-Use-intersphix-with-Debian-packages.patch +++ b/debian/patches/docs-Use-intersphix-with-Debian-packages.patch @@ -8,11 +8,11 @@ Forwarded: not-needed 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/conf.py b/docs/conf.py -index d58c17e..813e1c5 100644 +index 5cbbd4f..4dbd1dd 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -28,7 +28,7 @@ extlinks = { - "ghsa": ("https://github.com/advisories/%s", "GHSA-%s"), + "ghsa": ("https://github.com/advisories/GHSA-%s", "GHSA-%s"), } intersphinx_mapping = { - "python": ("https://docs.python.org/3/", None), diff --git a/debian/patches/series b/debian/patches/series index 1308be9..607f581 100644 --- a/debian/patches/series +++ b/debian/patches/series @@ -1,2 +1 @@ -tests-Preserve-any-existing-PYTHONPATH-in-tests.patch docs-Use-intersphix-with-Debian-packages.patch diff --git a/debian/patches/tests-Preserve-any-existing-PYTHONPATH-in-tests.patch b/debian/patches/tests-Preserve-any-existing-PYTHONPATH-in-tests.patch deleted file mode 100644 index 6706bdf..0000000 --- a/debian/patches/tests-Preserve-any-existing-PYTHONPATH-in-tests.patch +++ /dev/null @@ -1,31 +0,0 @@ -From: Lumir Balhar -Date: Tue, 22 Jun 2021 22:10:17 +0200 -Subject: tests: Preserve any existing PYTHONPATH in tests - -Forwarded: not-needed ---- - tests/conftest.py | 10 ++++++++-- - 1 file changed, 8 insertions(+), 2 deletions(-) - -diff --git a/tests/conftest.py b/tests/conftest.py -index b73202c..fd666c9 100644 ---- a/tests/conftest.py -+++ b/tests/conftest.py -@@ -103,9 +103,15 @@ def dev_server(xprocess, request, tmp_path): - class Starter(ProcessStarter): - args = [sys.executable, run_path, name, json.dumps(kwargs)] - # Extend the existing env, otherwise Windows and CI fails. -- # Modules will be imported from tmp_path for the reloader. -+ # Modules will be imported from tmp_path for the reloader -+ # but any existing PYTHONPATH is preserved. - # Unbuffered output so the logs update immediately. -- env = {**os.environ, "PYTHONPATH": str(tmp_path), "PYTHONUNBUFFERED": "1"} -+ original_python_path = os.getenv("PYTHONPATH") -+ if original_python_path: -+ new_python_path = os.pathsep.join((original_python_path, str(tmp_path))) -+ else: -+ new_python_path = str(tmp_path) -+ env = {**os.environ, "PYTHONPATH": new_python_path, "PYTHONUNBUFFERED": "1"} - - @cached_property - def pattern(self): diff --git a/debian/rules b/debian/rules index 8a7d89c..6b93674 100755 --- a/debian/rules +++ b/debian/rules @@ -3,14 +3,15 @@ #export DH_VERBOSE = 1 -include /usr/share/dpkg/pkg-info.mk - -BUILD_DATE = $(shell LC_ALL=C date -u "+%d %B %Y" -d "@$(SOURCE_DATE_EPOCH)") -SPHINXOPTS := -E -N -D html_last_updated_fmt="$(BUILD_DATE)" +SPHINXOPTS := -E -N export PYBUILD_NAME=werkzeug export PYBUILD_TEST_PYTEST=1 export PYBUILD_BEFORE_INSTALL=rm -rf {build_dir}/werkzeug/debug/shared/ICON_LICENSE.md +export PYBUILD_TEST_ARGS=--ignore tests/middleware/test_http_proxy.py --ignore tests/test_serving.py \ +'-k not test_basic \ +and not test_server \ +' %: dh $@ --buildsystem=pybuild diff --git a/docs/conf.py b/docs/conf.py index d58c17e..5cbbd4f 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -25,7 +25,7 @@ extlinks = { "issue": ("https://github.com/pallets/werkzeug/issues/%s", "#%s"), "pr": ("https://github.com/pallets/werkzeug/pull/%s", "#%s"), - "ghsa": ("https://github.com/advisories/%s", "GHSA-%s"), + "ghsa": ("https://github.com/advisories/GHSA-%s", "GHSA-%s"), } intersphinx_mapping = { "python": ("https://docs.python.org/3/", None), diff --git a/docs/datastructures.rst b/docs/datastructures.rst index 01432f4..e702525 100644 --- a/docs/datastructures.rst +++ b/docs/datastructures.rst @@ -27,10 +27,33 @@ General Purpose :members: :inherited-members: -.. autoclass:: OrderedMultiDict +.. class:: OrderedMultiDict -.. autoclass:: ImmutableMultiDict - :members: copy + Works like a regular :class:`MultiDict` but preserves the + order of the fields. To convert the ordered multi dict into a + list you can use the :meth:`items` method and pass it ``multi=True``. + + In general an :class:`OrderedMultiDict` is an order of magnitude + slower than a :class:`MultiDict`. + + .. admonition:: note + + Due to a limitation in Python you cannot convert an ordered + multi dict into a regular dict by using ``dict(multidict)``. + Instead you have to use the :meth:`to_dict` method, otherwise + the internal bucket objects are exposed. + + .. deprecated:: 3.1 + Will be removed in Werkzeug 3.2. Use ``MultiDict`` instead. + +.. class:: ImmutableMultiDict + + An immutable :class:`OrderedMultiDict`. + + .. deprecated:: 3.1 + Will be removed in Werkzeug 3.2. Use ``ImmutableMultiDict`` instead. + + .. versionadded:: 0.6 .. autoclass:: ImmutableOrderedMultiDict :members: copy @@ -69,26 +92,14 @@ HTTP Related .. autoclass:: LanguageAccept .. autoclass:: RequestCacheControl - :members: - - .. autoattribute:: no_cache - - .. autoattribute:: no_store - - .. autoattribute:: max_age - - .. autoattribute:: no_transform + :members: + :inherited-members: ImmutableDictMixin, CallbackDict + :member-order: groupwise .. autoclass:: ResponseCacheControl - :members: - - .. autoattribute:: no_cache - - .. autoattribute:: no_store - - .. autoattribute:: max_age - - .. autoattribute:: no_transform + :members: + :inherited-members: CallbackDict + :member-order: groupwise .. autoclass:: ETags :members: diff --git a/docs/exceptions.rst b/docs/exceptions.rst index 88a309d..d5b6970 100644 --- a/docs/exceptions.rst +++ b/docs/exceptions.rst @@ -44,6 +44,8 @@ The following error classes exist in Werkzeug: .. autoexception:: ImATeapot +.. autoexception:: MisdirectedRequest + .. autoexception:: UnprocessableEntity .. autoexception:: Locked diff --git a/docs/installation.rst b/docs/installation.rst index 7138f08..00513e1 100644 --- a/docs/installation.rst +++ b/docs/installation.rst @@ -6,7 +6,7 @@ Python Version -------------- We recommend using the latest version of Python. Werkzeug supports -Python 3.8 and newer. +Python 3.9 and newer. Optional dependencies diff --git a/docs/quickstart.rst b/docs/quickstart.rst index 0f3714e..d97764e 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -9,7 +9,7 @@ understanding of :pep:`3333` (WSGI) and :rfc:`2616` (HTTP). WSGI Environment -================ +---------------- The WSGI environment contains all the information the user request transmits to the application. It is passed to the WSGI application but you can also @@ -33,7 +33,7 @@ access the form data besides parsing that data by hand. Enter Request -============= +------------- For access to the request data the :class:`Request` object is much more fun. It wraps the `environ` and provides a read-only access to the data from @@ -112,7 +112,7 @@ The keys for the headers are of course case insensitive. Header Parsing -============== +-------------- There is more. Werkzeug provides convenient access to often used HTTP headers and other request data. @@ -141,7 +141,7 @@ the quality, the best item being the first: 'text/html' >>> 'application/xhtml+xml' in request.accept_mimetypes True ->>> print request.accept_mimetypes["application/json"] +>>> print(request.accept_mimetypes["application/json"]) 0.8 The same works for languages: @@ -183,7 +183,7 @@ True Responses -========= +--------- Response objects are the opposite of request objects. They are used to send data back to the client. In reality, response objects are nothing more than diff --git a/docs/request_data.rst b/docs/request_data.rst index b1c97b2..75811a9 100644 --- a/docs/request_data.rst +++ b/docs/request_data.rst @@ -79,16 +79,23 @@ request in such a way that the server uses too many resources to handle it. Each these limits will raise a :exc:`~werkzeug.exceptions.RequestEntityTooLarge` if they are exceeded. -- :attr:`~Request.max_content_length` Stop reading request data after this number +- :attr:`~Request.max_content_length` - Stop reading request data after this number of bytes. It's better to configure this in the WSGI server or HTTP server, rather than the WSGI application. -- :attr:`~Request.max_form_memory_size` Stop reading request data if any form part is - larger than this number of bytes. While file parts can be moved to disk, regular - form field data is stored in memory only. +- :attr:`~Request.max_form_memory_size` - Stop reading request data if any + non-file form field is larger than this number of bytes. While file parts + can be moved to disk, regular form field data is stored in memory only and + could fill up memory. The default is 500kB. - :attr:`~Request.max_form_parts` Stop reading request data if more than this number of parts are sent in multipart form data. This is useful to stop a very large number of very small parts, especially file parts. The default is 1000. +Each of these values can be set on the ``Request`` class to affect the default +for all requests, or on a ``request`` instance to change the behavior for a +specific request. For example, a small limit can be set by default, and a large +limit can be set on an endpoint that accepts video uploads. These values should +be tuned to the specific needs of your application and endpoints. + Using Werkzeug to set these limits is only one layer of protection. WSGI servers and HTTPS servers should set their own limits on size and timeouts. The operating system or container manager should set limits on memory and processing time for server diff --git a/docs/tutorial.rst b/docs/tutorial.rst index 943787a..9cb5aef 100644 --- a/docs/tutorial.rst +++ b/docs/tutorial.rst @@ -123,7 +123,7 @@ if they are not used right away, to keep it from being confusing:: import os import redis - from werkzeug.urls import url_parse + from urllib.parse import urlparse from werkzeug.wrappers import Request, Response from werkzeug.routing import Map, Rule from werkzeug.exceptions import HTTPException, NotFound @@ -308,7 +308,7 @@ we need to write a function and a helper method. For URL validation this is good enough:: def is_valid_url(url): - parts = url_parse(url) + parts = urlparse(url) return parts.scheme in ('http', 'https') For inserting the URL, all we need is this little method on our class:: diff --git a/pyproject.toml b/pyproject.toml index eb06882..2d5a6ce 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "Werkzeug" -version = "3.0.3" +version = "3.1.3" description = "The comprehensive WSGI web application library." readme = "README.md" license = {file = "LICENSE.txt"} @@ -19,7 +19,7 @@ classifiers = [ "Topic :: Software Development :: Libraries :: Application Frameworks", "Typing :: Typed", ] -requires-python = ">=3.8" +requires-python = ">=3.9" dependencies = [ "MarkupSafe>=2.1.1", ] @@ -70,6 +70,7 @@ source = ["werkzeug", "tests"] source = ["src", "*/site-packages"] [tool.mypy] +python_version = "3.9" files = ["src/werkzeug"] show_error_codes = true pretty = true @@ -79,16 +80,14 @@ strict = true module = [ "colorama.*", "cryptography.*", - "eventlet.*", - "gevent.*", - "greenlet.*", + "ephemeral_port_reserve", "watchdog.*", "xprocess.*", ] ignore_missing_imports = true [tool.pyright] -pythonVersion = "3.8" +pythonVersion = "3.9" include = ["src/werkzeug"] [tool.ruff] @@ -110,8 +109,12 @@ select = [ ignore = [ "E402", # allow circular imports at end of file ] -ignore-init-module-imports = true [tool.ruff.lint.isort] force-single-line = true order-by-type = false + +[tool.gha-update] +tag-only = [ + "slsa-framework/slsa-github-generator", +] diff --git a/requirements/build.txt b/requirements/build.txt index 9ecc489..1b13b05 100644 --- a/requirements/build.txt +++ b/requirements/build.txt @@ -1,12 +1,12 @@ # -# This file is autogenerated by pip-compile with Python 3.12 +# This file is autogenerated by pip-compile with Python 3.13 # by the following command: # # pip-compile build.in # -build==1.2.1 +build==1.2.2.post1 # via -r build.in -packaging==24.0 +packaging==24.1 # via build -pyproject-hooks==1.0.0 +pyproject-hooks==1.2.0 # via build diff --git a/requirements/dev.txt b/requirements/dev.txt index 186ceda..24eb34a 100644 --- a/requirements/dev.txt +++ b/requirements/dev.txt @@ -1,24 +1,24 @@ # -# This file is autogenerated by pip-compile with Python 3.12 +# This file is autogenerated by pip-compile with Python 3.13 # by the following command: # # pip-compile dev.in # -alabaster==0.7.16 +alabaster==1.0.0 # via # -r docs.txt # sphinx -babel==2.14.0 +babel==2.16.0 # via # -r docs.txt # sphinx -cachetools==5.3.3 +cachetools==5.5.0 # via tox -certifi==2024.2.2 +certifi==2024.8.30 # via # -r docs.txt # requests -cffi==1.16.0 +cffi==1.17.1 # via # -r tests.txt # cryptography @@ -26,31 +26,29 @@ cfgv==3.4.0 # via pre-commit chardet==5.2.0 # via tox -charset-normalizer==3.3.2 +charset-normalizer==3.4.0 # via # -r docs.txt # requests colorama==0.4.6 # via tox -cryptography==42.0.5 +cryptography==43.0.3 # via -r tests.txt -distlib==0.3.8 +distlib==0.3.9 # via virtualenv -docutils==0.20.1 +docutils==0.21.2 # via # -r docs.txt # sphinx ephemeral-port-reserve==1.1.4 # via -r tests.txt -filelock==3.13.3 +filelock==3.16.1 # via # tox # virtualenv -greenlet==3.0.3 - # via -r tests.txt -identify==2.5.35 +identify==2.6.1 # via pre-commit -idna==3.6 +idna==3.10 # via # -r docs.txt # requests @@ -63,26 +61,26 @@ iniconfig==2.0.0 # -r tests.txt # -r typing.txt # pytest -jinja2==3.1.3 +jinja2==3.1.4 # via # -r docs.txt # sphinx -markupsafe==2.1.5 +markupsafe==3.0.2 # via # -r docs.txt # jinja2 -mypy==1.9.0 +mypy==1.13.0 # via -r typing.txt mypy-extensions==1.0.0 # via # -r typing.txt # mypy -nodeenv==1.8.0 +nodeenv==1.9.1 # via # -r typing.txt # pre-commit # pyright -packaging==24.0 +packaging==24.1 # via # -r docs.txt # -r tests.txt @@ -92,49 +90,42 @@ packaging==24.0 # pytest # sphinx # tox -pallets-sphinx-themes==2.1.1 +pallets-sphinx-themes==2.3.0 # via -r docs.txt -platformdirs==4.2.0 +platformdirs==4.3.6 # via # tox # virtualenv -pluggy==1.4.0 +pluggy==1.5.0 # via # -r tests.txt # -r typing.txt # pytest # tox -pre-commit==3.7.0 +pre-commit==4.0.1 # via -r dev.in -psutil==5.9.8 - # via - # -r tests.txt - # pytest-xprocess pycparser==2.22 # via # -r tests.txt # cffi -pygments==2.17.2 +pygments==2.18.0 # via # -r docs.txt # sphinx -pyproject-api==1.6.1 +pyproject-api==1.8.0 # via tox -pyright==1.1.357 +pyright==1.1.386 # via -r typing.txt -pytest==8.1.1 +pytest==8.3.3 # via # -r tests.txt # -r typing.txt # pytest-timeout - # pytest-xprocess pytest-timeout==2.3.1 # via -r tests.txt -pytest-xprocess==0.23.0 - # via -r tests.txt -pyyaml==6.0.1 +pyyaml==6.0.2 # via pre-commit -requests==2.31.0 +requests==2.32.3 # via # -r docs.txt # sphinx @@ -142,20 +133,25 @@ snowballstemmer==2.2.0 # via # -r docs.txt # sphinx -sphinx==7.2.6 +sphinx==8.1.3 # via # -r docs.txt # pallets-sphinx-themes + # sphinx-notfound-page # sphinxcontrib-log-cabinet -sphinxcontrib-applehelp==1.0.8 +sphinx-notfound-page==1.0.4 + # via + # -r docs.txt + # pallets-sphinx-themes +sphinxcontrib-applehelp==2.0.0 # via # -r docs.txt # sphinx -sphinxcontrib-devhelp==1.0.6 +sphinxcontrib-devhelp==2.0.0 # via # -r docs.txt # sphinx -sphinxcontrib-htmlhelp==2.0.5 +sphinxcontrib-htmlhelp==2.1.0 # via # -r docs.txt # sphinx @@ -165,38 +161,36 @@ sphinxcontrib-jsmath==1.0.1 # sphinx sphinxcontrib-log-cabinet==1.0.1 # via -r docs.txt -sphinxcontrib-qthelp==1.0.7 +sphinxcontrib-qthelp==2.0.0 # via # -r docs.txt # sphinx -sphinxcontrib-serializinghtml==1.1.10 +sphinxcontrib-serializinghtml==2.0.0 # via # -r docs.txt # sphinx -tox==4.14.2 +tox==4.23.2 # via -r dev.in types-contextvars==2.4.7.3 # via -r typing.txt types-dataclasses==0.6.6 # via -r typing.txt -types-setuptools==69.2.0.20240317 +types-setuptools==75.2.0.20241019 # via -r typing.txt -typing-extensions==4.11.0 +typing-extensions==4.12.2 # via # -r typing.txt # mypy -urllib3==2.2.1 + # pyright +urllib3==2.2.3 # via # -r docs.txt # requests -virtualenv==20.25.1 +virtualenv==20.27.0 # via # pre-commit # tox -watchdog==4.0.0 +watchdog==5.0.3 # via # -r tests.txt # -r typing.txt - -# The following packages are considered to be unsafe in a requirements file: -# setuptools diff --git a/requirements/docs.txt b/requirements/docs.txt index ed605ea..1e3a54e 100644 --- a/requirements/docs.txt +++ b/requirements/docs.txt @@ -1,57 +1,60 @@ # -# This file is autogenerated by pip-compile with Python 3.12 +# This file is autogenerated by pip-compile with Python 3.13 # by the following command: # # pip-compile docs.in # -alabaster==0.7.16 +alabaster==1.0.0 # via sphinx -babel==2.14.0 +babel==2.16.0 # via sphinx -certifi==2024.2.2 +certifi==2024.8.30 # via requests -charset-normalizer==3.3.2 +charset-normalizer==3.4.0 # via requests -docutils==0.20.1 +docutils==0.21.2 # via sphinx -idna==3.6 +idna==3.10 # via requests imagesize==1.4.1 # via sphinx -jinja2==3.1.3 +jinja2==3.1.4 # via sphinx -markupsafe==2.1.5 +markupsafe==3.0.2 # via jinja2 -packaging==24.0 +packaging==24.1 # via # pallets-sphinx-themes # sphinx -pallets-sphinx-themes==2.1.1 +pallets-sphinx-themes==2.3.0 # via -r docs.in -pygments==2.17.2 +pygments==2.18.0 # via sphinx -requests==2.31.0 +requests==2.32.3 # via sphinx snowballstemmer==2.2.0 # via sphinx -sphinx==7.2.6 +sphinx==8.1.3 # via # -r docs.in # pallets-sphinx-themes + # sphinx-notfound-page # sphinxcontrib-log-cabinet -sphinxcontrib-applehelp==1.0.8 +sphinx-notfound-page==1.0.4 + # via pallets-sphinx-themes +sphinxcontrib-applehelp==2.0.0 # via sphinx -sphinxcontrib-devhelp==1.0.6 +sphinxcontrib-devhelp==2.0.0 # via sphinx -sphinxcontrib-htmlhelp==2.0.5 +sphinxcontrib-htmlhelp==2.1.0 # via sphinx sphinxcontrib-jsmath==1.0.1 # via sphinx sphinxcontrib-log-cabinet==1.0.1 # via -r docs.in -sphinxcontrib-qthelp==1.0.7 +sphinxcontrib-qthelp==2.0.0 # via sphinx -sphinxcontrib-serializinghtml==1.1.10 +sphinxcontrib-serializinghtml==2.0.0 # via sphinx -urllib3==2.2.1 +urllib3==2.2.3 # via requests diff --git a/requirements/tests.in b/requirements/tests.in index 8228f8e..c1b5bc3 100644 --- a/requirements/tests.in +++ b/requirements/tests.in @@ -1,8 +1,6 @@ pytest pytest-timeout -# pinned for python 3.8 support -pytest-xprocess<1 cryptography -greenlet watchdog ephemeral-port-reserve +cffi diff --git a/requirements/tests.txt b/requirements/tests.txt index 14b6743..d64cace 100644 --- a/requirements/tests.txt +++ b/requirements/tests.txt @@ -1,35 +1,30 @@ # -# This file is autogenerated by pip-compile with Python 3.12 +# This file is autogenerated by pip-compile with Python 3.13 # by the following command: # # pip-compile tests.in # -cffi==1.16.0 - # via cryptography -cryptography==42.0.5 +cffi==1.17.1 + # via + # -r tests.in + # cryptography +cryptography==43.0.3 # via -r tests.in ephemeral-port-reserve==1.1.4 # via -r tests.in -greenlet==3.0.3 - # via -r tests.in iniconfig==2.0.0 # via pytest -packaging==24.0 +packaging==24.1 # via pytest -pluggy==1.4.0 +pluggy==1.5.0 # via pytest -psutil==5.9.8 - # via pytest-xprocess pycparser==2.22 # via cffi -pytest==8.1.1 +pytest==8.3.3 # via # -r tests.in # pytest-timeout - # pytest-xprocess pytest-timeout==2.3.1 # via -r tests.in -pytest-xprocess==0.23.0 - # via -r tests.in -watchdog==4.0.0 +watchdog==5.0.3 # via -r tests.in diff --git a/requirements/typing.txt b/requirements/typing.txt index 09c78d7..b90f838 100644 --- a/requirements/typing.txt +++ b/requirements/typing.txt @@ -1,35 +1,34 @@ # -# This file is autogenerated by pip-compile with Python 3.12 +# This file is autogenerated by pip-compile with Python 3.13 # by the following command: # # pip-compile typing.in # iniconfig==2.0.0 # via pytest -mypy==1.9.0 +mypy==1.13.0 # via -r typing.in mypy-extensions==1.0.0 # via mypy -nodeenv==1.8.0 +nodeenv==1.9.1 # via pyright -packaging==24.0 +packaging==24.1 # via pytest -pluggy==1.4.0 +pluggy==1.5.0 # via pytest -pyright==1.1.357 +pyright==1.1.386 # via -r typing.in -pytest==8.1.1 +pytest==8.3.3 # via -r typing.in types-contextvars==2.4.7.3 # via -r typing.in types-dataclasses==0.6.6 # via -r typing.in -types-setuptools==69.2.0.20240317 +types-setuptools==75.2.0.20241019 # via -r typing.in -typing-extensions==4.11.0 - # via mypy -watchdog==4.0.0 +typing-extensions==4.12.2 + # via + # mypy + # pyright +watchdog==5.0.3 # via -r typing.in - -# The following packages are considered to be unsafe in a requirements file: -# setuptools diff --git a/src/werkzeug/__init__.py b/src/werkzeug/__init__.py index 57cb753..0b248fd 100644 --- a/src/werkzeug/__init__.py +++ b/src/werkzeug/__init__.py @@ -1,25 +1,4 @@ -from __future__ import annotations - -import typing as t - from .serving import run_simple as run_simple from .test import Client as Client from .wrappers import Request as Request from .wrappers import Response as Response - - -def __getattr__(name: str) -> t.Any: - if name == "__version__": - import importlib.metadata - import warnings - - warnings.warn( - "The '__version__' attribute is deprecated and will be removed in" - " Werkzeug 3.1. Use feature detection or" - " 'importlib.metadata.version(\"werkzeug\")' instead.", - DeprecationWarning, - stacklevel=2, - ) - return importlib.metadata.version("werkzeug") - - raise AttributeError(name) diff --git a/src/werkzeug/_reloader.py b/src/werkzeug/_reloader.py index d7e91a6..8fd50b9 100644 --- a/src/werkzeug/_reloader.py +++ b/src/werkzeug/_reloader.py @@ -281,7 +281,7 @@ def trigger_reload(self, filename: str) -> None: self.log_reload(filename) sys.exit(3) - def log_reload(self, filename: str) -> None: + def log_reload(self, filename: str | bytes) -> None: filename = os.path.abspath(filename) _log("info", f" * Detected change in {filename!r}, reloading") @@ -312,7 +312,11 @@ def run_step(self) -> None: class WatchdogReloaderLoop(ReloaderLoop): def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: - from watchdog.events import EVENT_TYPE_OPENED + from watchdog.events import EVENT_TYPE_CLOSED + from watchdog.events import EVENT_TYPE_CREATED + from watchdog.events import EVENT_TYPE_DELETED + from watchdog.events import EVENT_TYPE_MODIFIED + from watchdog.events import EVENT_TYPE_MOVED from watchdog.events import FileModifiedEvent from watchdog.events import PatternMatchingEventHandler from watchdog.observers import Observer @@ -322,7 +326,14 @@ def __init__(self, *args: t.Any, **kwargs: t.Any) -> None: class EventHandler(PatternMatchingEventHandler): def on_any_event(self, event: FileModifiedEvent): # type: ignore - if event.event_type == EVENT_TYPE_OPENED: + if event.event_type not in { + EVENT_TYPE_CLOSED, + EVENT_TYPE_CREATED, + EVENT_TYPE_DELETED, + EVENT_TYPE_MODIFIED, + EVENT_TYPE_MOVED, + }: + # skip events that don't involve changes to the file return trigger_reload(event.src_path) @@ -340,7 +351,7 @@ def on_any_event(self, event: FileModifiedEvent): # type: ignore # the source file (or initial pyc file) as well. Ignore Git and # Mercurial internal changes. extra_patterns = [p for p in self.extra_files if not os.path.isdir(p)] - self.event_handler = EventHandler( # type: ignore[no-untyped-call] + self.event_handler = EventHandler( patterns=["*.py", "*.pyc", "*.zip", *extra_patterns], ignore_patterns=[ *[f"*/{d}/*" for d in _ignore_common_dirs], @@ -349,7 +360,7 @@ def on_any_event(self, event: FileModifiedEvent): # type: ignore ) self.should_reload = False - def trigger_reload(self, filename: str) -> None: + def trigger_reload(self, filename: str | bytes) -> None: # This is called inside an event handler, which means throwing # SystemExit has no effect. # https://github.com/gorakhargosh/watchdog/issues/294 @@ -358,11 +369,11 @@ def trigger_reload(self, filename: str) -> None: def __enter__(self) -> ReloaderLoop: self.watches: dict[str, t.Any] = {} - self.observer.start() # type: ignore[no-untyped-call] + self.observer.start() return super().__enter__() def __exit__(self, exc_type, exc_val, exc_tb): # type: ignore - self.observer.stop() # type: ignore[no-untyped-call] + self.observer.stop() self.observer.join() def run(self) -> None: @@ -378,7 +389,7 @@ def run_step(self) -> None: for path in _find_watchdog_paths(self.extra_files, self.exclude_patterns): if path not in self.watches: try: - self.watches[path] = self.observer.schedule( # type: ignore[no-untyped-call] + self.watches[path] = self.observer.schedule( self.event_handler, path, recursive=True ) except OSError: @@ -393,7 +404,7 @@ def run_step(self) -> None: watch = self.watches.pop(path, None) if watch is not None: - self.observer.unschedule(watch) # type: ignore[no-untyped-call] + self.observer.unschedule(watch) reloader_loops: dict[str, type[ReloaderLoop]] = { diff --git a/src/werkzeug/datastructures/__init__.py b/src/werkzeug/datastructures/__init__.py index 846ffce..6582de0 100644 --- a/src/werkzeug/datastructures/__init__.py +++ b/src/werkzeug/datastructures/__init__.py @@ -1,3 +1,7 @@ +from __future__ import annotations + +import typing as t + from .accept import Accept as Accept from .accept import CharsetAccept as CharsetAccept from .accept import LanguageAccept as LanguageAccept @@ -26,9 +30,35 @@ from .structures import ImmutableDict as ImmutableDict from .structures import ImmutableList as ImmutableList from .structures import ImmutableMultiDict as ImmutableMultiDict -from .structures import ImmutableOrderedMultiDict as ImmutableOrderedMultiDict from .structures import ImmutableTypeConversionDict as ImmutableTypeConversionDict from .structures import iter_multi_items as iter_multi_items from .structures import MultiDict as MultiDict -from .structures import OrderedMultiDict as OrderedMultiDict from .structures import TypeConversionDict as TypeConversionDict + + +def __getattr__(name: str) -> t.Any: + import warnings + + if name == "OrderedMultiDict": + from .structures import _OrderedMultiDict + + warnings.warn( + "'OrderedMultiDict' is deprecated and will be removed in Werkzeug" + " 3.2. Use 'MultiDict' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _OrderedMultiDict + + if name == "ImmutableOrderedMultiDict": + from .structures import _ImmutableOrderedMultiDict + + warnings.warn( + "'OrderedMultiDict' is deprecated and will be removed in Werkzeug" + " 3.2. Use 'ImmutableMultiDict' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _ImmutableOrderedMultiDict + + raise AttributeError(name) diff --git a/src/werkzeug/datastructures/accept.py b/src/werkzeug/datastructures/accept.py index d80f0bb..44179a9 100644 --- a/src/werkzeug/datastructures/accept.py +++ b/src/werkzeug/datastructures/accept.py @@ -1,12 +1,14 @@ from __future__ import annotations import codecs +import collections.abc as cabc import re +import typing as t from .structures import ImmutableList -class Accept(ImmutableList): +class Accept(ImmutableList[tuple[str, float]]): """An :class:`Accept` object is just a list subclass for lists of ``(value, quality)`` tuples. It is automatically sorted by specificity and quality. @@ -42,29 +44,39 @@ class Accept(ImmutableList): """ - def __init__(self, values=()): + def __init__( + self, values: Accept | cabc.Iterable[tuple[str, float]] | None = () + ) -> None: if values is None: - list.__init__(self) + super().__init__() self.provided = False elif isinstance(values, Accept): self.provided = values.provided - list.__init__(self, values) + super().__init__(values) else: self.provided = True values = sorted( values, key=lambda x: (self._specificity(x[0]), x[1]), reverse=True ) - list.__init__(self, values) + super().__init__(values) - def _specificity(self, value): + def _specificity(self, value: str) -> tuple[bool, ...]: """Returns a tuple describing the value's specificity.""" return (value != "*",) - def _value_matches(self, value, item): + def _value_matches(self, value: str, item: str) -> bool: """Check if a value matches a given accept item.""" return item == "*" or item.lower() == value.lower() - def __getitem__(self, key): + @t.overload + def __getitem__(self, key: str) -> float: ... + @t.overload + def __getitem__(self, key: t.SupportsIndex) -> tuple[str, float]: ... + @t.overload + def __getitem__(self, key: slice) -> list[tuple[str, float]]: ... + def __getitem__( + self, key: str | t.SupportsIndex | slice + ) -> float | tuple[str, float] | list[tuple[str, float]]: """Besides index lookup (getting item n) you can also pass it a string to get the quality for the item. If the item is not in the list, the returned quality is ``0``. @@ -73,7 +85,7 @@ def __getitem__(self, key): return self.quality(key) return list.__getitem__(self, key) - def quality(self, key): + def quality(self, key: str) -> float: """Returns the quality of the key. .. versionadded:: 0.6 @@ -85,17 +97,17 @@ def quality(self, key): return quality return 0 - def __contains__(self, value): + def __contains__(self, value: str) -> bool: # type: ignore[override] for item, _quality in self: if self._value_matches(value, item): return True return False - def __repr__(self): + def __repr__(self) -> str: pairs_str = ", ".join(f"({x!r}, {y})" for x, y in self) return f"{type(self).__name__}([{pairs_str}])" - def index(self, key): + def index(self, key: str | tuple[str, float]) -> int: # type: ignore[override] """Get the position of an entry or raise :exc:`ValueError`. :param key: The key to be looked up. @@ -111,7 +123,7 @@ def index(self, key): raise ValueError(key) return list.index(self, key) - def find(self, key): + def find(self, key: str | tuple[str, float]) -> int: """Get the position of an entry or return -1. :param key: The key to be looked up. @@ -121,12 +133,12 @@ def find(self, key): except ValueError: return -1 - def values(self): + def values(self) -> cabc.Iterator[str]: """Iterate over all values.""" for item in self: yield item[0] - def to_header(self): + def to_header(self) -> str: """Convert the header set into an HTTP header string.""" result = [] for value, quality in self: @@ -135,17 +147,23 @@ def to_header(self): result.append(value) return ",".join(result) - def __str__(self): + def __str__(self) -> str: return self.to_header() - def _best_single_match(self, match): + def _best_single_match(self, match: str) -> tuple[str, float] | None: for client_item, quality in self: if self._value_matches(match, client_item): # self is sorted by specificity descending, we can exit return client_item, quality return None - def best_match(self, matches, default=None): + @t.overload + def best_match(self, matches: cabc.Iterable[str]) -> str | None: ... + @t.overload + def best_match(self, matches: cabc.Iterable[str], default: str = ...) -> str: ... + def best_match( + self, matches: cabc.Iterable[str], default: str | None = None + ) -> str | None: """Returns the best match from a list of possible matches based on the specificity and quality of the client. If two items have the same quality and specificity, the one is returned that comes first. @@ -154,8 +172,8 @@ def best_match(self, matches, default=None): :param default: the value that is returned if none match """ result = default - best_quality = -1 - best_specificity = (-1,) + best_quality: float = -1 + best_specificity: tuple[float, ...] = (-1,) for server_item in matches: match = self._best_single_match(server_item) if not match: @@ -172,16 +190,18 @@ def best_match(self, matches, default=None): return result @property - def best(self): + def best(self) -> str | None: """The best match as value.""" if self: return self[0][0] + return None + _mime_split_re = re.compile(r"/|(?:\s*;\s*)") -def _normalize_mime(value): +def _normalize_mime(value: str) -> list[str]: return _mime_split_re.split(value.lower()) @@ -190,10 +210,10 @@ class MIMEAccept(Accept): mimetypes. """ - def _specificity(self, value): + def _specificity(self, value: str) -> tuple[bool, ...]: return tuple(x != "*" for x in _mime_split_re.split(value)) - def _value_matches(self, value, item): + def _value_matches(self, value: str, item: str) -> bool: # item comes from the client, can't match if it's invalid. if "/" not in item: return False @@ -234,27 +254,25 @@ def _value_matches(self, value, item): ) @property - def accept_html(self): + def accept_html(self) -> bool: """True if this object accepts HTML.""" - return ( - "text/html" in self or "application/xhtml+xml" in self or self.accept_xhtml - ) + return "text/html" in self or self.accept_xhtml # type: ignore[comparison-overlap] @property - def accept_xhtml(self): + def accept_xhtml(self) -> bool: """True if this object accepts XHTML.""" - return "application/xhtml+xml" in self or "application/xml" in self + return "application/xhtml+xml" in self or "application/xml" in self # type: ignore[comparison-overlap] @property - def accept_json(self): + def accept_json(self) -> bool: """True if this object accepts JSON.""" - return "application/json" in self + return "application/json" in self # type: ignore[comparison-overlap] _locale_delim_re = re.compile(r"[_-]") -def _normalize_lang(value): +def _normalize_lang(value: str) -> list[str]: """Process a language tag for matching.""" return _locale_delim_re.split(value.lower()) @@ -262,10 +280,16 @@ def _normalize_lang(value): class LanguageAccept(Accept): """Like :class:`Accept` but with normalization for language tags.""" - def _value_matches(self, value, item): + def _value_matches(self, value: str, item: str) -> bool: return item == "*" or _normalize_lang(value) == _normalize_lang(item) - def best_match(self, matches, default=None): + @t.overload + def best_match(self, matches: cabc.Iterable[str]) -> str | None: ... + @t.overload + def best_match(self, matches: cabc.Iterable[str], default: str = ...) -> str: ... + def best_match( + self, matches: cabc.Iterable[str], default: str | None = None + ) -> str | None: """Given a list of supported values, finds the best match from the list of accepted values. @@ -316,8 +340,8 @@ def best_match(self, matches, default=None): class CharsetAccept(Accept): """Like :class:`Accept` but with normalization for charsets.""" - def _value_matches(self, value, item): - def _normalize(name): + def _value_matches(self, value: str, item: str) -> bool: + def _normalize(name: str) -> str: try: return codecs.lookup(name).name except LookupError: diff --git a/src/werkzeug/datastructures/accept.pyi b/src/werkzeug/datastructures/accept.pyi deleted file mode 100644 index 4b74dd9..0000000 --- a/src/werkzeug/datastructures/accept.pyi +++ /dev/null @@ -1,54 +0,0 @@ -from collections.abc import Iterable -from collections.abc import Iterator -from typing import overload - -from .structures import ImmutableList - -class Accept(ImmutableList[tuple[str, int]]): - provided: bool - def __init__( - self, values: Accept | Iterable[tuple[str, float]] | None = None - ) -> None: ... - def _specificity(self, value: str) -> tuple[bool, ...]: ... - def _value_matches(self, value: str, item: str) -> bool: ... - @overload # type: ignore - def __getitem__(self, key: str) -> int: ... - @overload - def __getitem__(self, key: int) -> tuple[str, int]: ... - @overload - def __getitem__(self, key: slice) -> Iterable[tuple[str, int]]: ... - def quality(self, key: str) -> int: ... - def __contains__(self, value: str) -> bool: ... # type: ignore - def index(self, key: str) -> int: ... # type: ignore - def find(self, key: str) -> int: ... - def values(self) -> Iterator[str]: ... - def to_header(self) -> str: ... - def _best_single_match(self, match: str) -> tuple[str, int] | None: ... - @overload - def best_match(self, matches: Iterable[str], default: str) -> str: ... - @overload - def best_match( - self, matches: Iterable[str], default: str | None = None - ) -> str | None: ... - @property - def best(self) -> str: ... - -def _normalize_mime(value: str) -> list[str]: ... - -class MIMEAccept(Accept): - def _specificity(self, value: str) -> tuple[bool, ...]: ... - def _value_matches(self, value: str, item: str) -> bool: ... - @property - def accept_html(self) -> bool: ... - @property - def accept_xhtml(self) -> bool: ... - @property - def accept_json(self) -> bool: ... - -def _normalize_lang(value: str) -> list[str]: ... - -class LanguageAccept(Accept): - def _value_matches(self, value: str, item: str) -> bool: ... - -class CharsetAccept(Accept): - def _value_matches(self, value: str, item: str) -> bool: ... diff --git a/src/werkzeug/datastructures/auth.py b/src/werkzeug/datastructures/auth.py index a3ca0de..42f7aa4 100644 --- a/src/werkzeug/datastructures/auth.py +++ b/src/werkzeug/datastructures/auth.py @@ -2,6 +2,7 @@ import base64 import binascii +import collections.abc as cabc import typing as t from ..http import dump_header @@ -176,7 +177,7 @@ def __init__( values, lambda _: self._trigger_on_update() ) self._token = token - self._on_update: t.Callable[[WWWAuthenticate], None] | None = None + self._on_update: cabc.Callable[[WWWAuthenticate], None] | None = None def _trigger_on_update(self) -> None: if self._on_update is not None: diff --git a/src/werkzeug/datastructures/cache_control.py b/src/werkzeug/datastructures/cache_control.py index bff4c18..8d700ab 100644 --- a/src/werkzeug/datastructures/cache_control.py +++ b/src/werkzeug/datastructures/cache_control.py @@ -1,25 +1,59 @@ from __future__ import annotations +import collections.abc as cabc +import typing as t +from inspect import cleandoc + from .mixins import ImmutableDictMixin -from .mixins import UpdateDictMixin +from .structures import CallbackDict -def cache_control_property(key, empty, type): +def cache_control_property( + key: str, empty: t.Any, type: type[t.Any] | None, *, doc: str | None = None +) -> t.Any: """Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass. + :param key: The attribute name present in the parsed cache-control header dict. + :param empty: The value to use if the key is present without a value. + :param type: The type to convert the string value to instead of a string. If + conversion raises a ``ValueError``, the returned value is ``None``. + :param doc: The docstring for the property. If not given, it is generated + based on the other params. + + .. versionchanged:: 3.1 + Added the ``doc`` param. + .. versionchanged:: 2.0 Renamed from ``cache_property``. """ + if doc is None: + parts = [f"The ``{key}`` attribute."] + + if type is bool: + parts.append("A ``bool``, either present or not.") + else: + if type is None: + parts.append("A ``str``,") + else: + parts.append(f"A ``{type.__name__}``,") + + if empty is not None: + parts.append(f"``{empty!r}`` if present with no value,") + + parts.append("or ``None`` if not present.") + + doc = " ".join(parts) + return property( lambda x: x._get_cache_value(key, empty, type), lambda x, v: x._set_cache_value(key, v, type), lambda x: x._del_cache_value(key), - f"accessor for {key!r}", + doc=cleandoc(doc), ) -class _CacheControl(UpdateDictMixin, dict): +class _CacheControl(CallbackDict[str, t.Optional[str]]): """Subclass of a dict that stores values for a Cache-Control header. It has accessors for all the cache-control directives specified in RFC 2616. The class does not differentiate between request and response directives. @@ -32,93 +66,95 @@ class _CacheControl(UpdateDictMixin, dict): to subclass it and add your own items have a look at the sourcecode for that class. - .. versionchanged:: 2.1.0 + .. versionchanged:: 3.1 + Dict values are always ``str | None``. Setting properties will + convert the value to a string. Setting a non-bool property to + ``False`` is equivalent to setting it to ``None``. Getting typed + properties will return ``None`` if conversion raises + ``ValueError``, rather than the string. + + .. versionchanged:: 2.1 Setting int properties such as ``max_age`` will convert the value to an int. .. versionchanged:: 0.4 - - Setting `no_cache` or `private` to boolean `True` will set the implicit - none-value which is ``*``: - - >>> cc = ResponseCacheControl() - >>> cc.no_cache = True - >>> cc - - >>> cc.no_cache - '*' - >>> cc.no_cache = None - >>> cc - - - In versions before 0.5 the behavior documented here affected the now - no longer existing `CacheControl` class. + Setting ``no_cache`` or ``private`` to ``True`` will set the + implicit value ``"*"``. """ - no_cache = cache_control_property("no-cache", "*", None) - no_store = cache_control_property("no-store", None, bool) - max_age = cache_control_property("max-age", -1, int) - no_transform = cache_control_property("no-transform", None, None) - - def __init__(self, values=(), on_update=None): - dict.__init__(self, values or ()) - self.on_update = on_update + no_store: bool = cache_control_property("no-store", None, bool) + max_age: int | None = cache_control_property("max-age", None, int) + no_transform: bool = cache_control_property("no-transform", None, bool) + stale_if_error: int | None = cache_control_property("stale-if-error", None, int) + + def __init__( + self, + values: cabc.Mapping[str, t.Any] | cabc.Iterable[tuple[str, t.Any]] | None = (), + on_update: cabc.Callable[[_CacheControl], None] | None = None, + ): + super().__init__(values, on_update) self.provided = values is not None - def _get_cache_value(self, key, empty, type): + def _get_cache_value( + self, key: str, empty: t.Any, type: type[t.Any] | None + ) -> t.Any: """Used internally by the accessor properties.""" if type is bool: return key in self - if key in self: - value = self[key] - if value is None: - return empty - elif type is not None: - try: - value = type(value) - except ValueError: - pass - return value - return None - - def _set_cache_value(self, key, value, type): + + if key not in self: + return None + + if (value := self[key]) is None: + return empty + + if type is not None: + try: + value = type(value) + except ValueError: + return None + + return value + + def _set_cache_value( + self, key: str, value: t.Any, type: type[t.Any] | None + ) -> None: """Used internally by the accessor properties.""" if type is bool: if value: self[key] = None else: self.pop(key, None) + elif value is None or value is False: + self.pop(key, None) + elif value is True: + self[key] = None else: - if value is None: - self.pop(key, None) - elif value is True: - self[key] = None - else: - if type is not None: - self[key] = type(value) - else: - self[key] = value + if type is not None: + value = type(value) - def _del_cache_value(self, key): + self[key] = str(value) + + def _del_cache_value(self, key: str) -> None: """Used internally by the accessor properties.""" if key in self: del self[key] - def to_header(self): + def to_header(self) -> str: """Convert the stored values into a cache control header.""" return http.dump_header(self) - def __str__(self): + def __str__(self) -> str: return self.to_header() - def __repr__(self): + def __repr__(self) -> str: kv_str = " ".join(f"{k}={v!r}" for k, v in sorted(self.items())) return f"<{type(self).__name__} {kv_str}>" cache_property = staticmethod(cache_control_property) -class RequestCacheControl(ImmutableDictMixin, _CacheControl): +class RequestCacheControl(ImmutableDictMixin[str, t.Optional[str]], _CacheControl): # type: ignore[misc] """A cache control for requests. This is immutable and gives access to all the request-relevant cache control headers. @@ -127,18 +163,49 @@ class RequestCacheControl(ImmutableDictMixin, _CacheControl): you plan to subclass it and add your own items have a look at the sourcecode for that class. - .. versionchanged:: 2.1.0 + .. versionchanged:: 3.1 + Dict values are always ``str | None``. Setting properties will + convert the value to a string. Setting a non-bool property to + ``False`` is equivalent to setting it to ``None``. Getting typed + properties will return ``None`` if conversion raises + ``ValueError``, rather than the string. + + .. versionchanged:: 3.1 + ``max_age`` is ``None`` if present without a value, rather + than ``-1``. + + .. versionchanged:: 3.1 + ``no_cache`` is a boolean, it is ``True`` instead of ``"*"`` + when present. + + .. versionchanged:: 3.1 + ``max_stale`` is ``True`` if present without a value, rather + than ``"*"``. + + .. versionchanged:: 3.1 + ``no_transform`` is a boolean. Previously it was mistakenly + always ``None``. + + .. versionchanged:: 3.1 + ``min_fresh`` is ``None`` if present without a value, rather + than ``"*"``. + + .. versionchanged:: 2.1 Setting int properties such as ``max_age`` will convert the value to an int. .. versionadded:: 0.5 - In previous versions a `CacheControl` class existed that was used - both for request and response. + Response-only properties are not present on this request class. """ - max_stale = cache_control_property("max-stale", "*", int) - min_fresh = cache_control_property("min-fresh", "*", int) - only_if_cached = cache_control_property("only-if-cached", None, bool) + no_cache: bool = cache_control_property("no-cache", None, bool) + max_stale: int | t.Literal[True] | None = cache_control_property( + "max-stale", + True, + int, + ) + min_fresh: int | None = cache_control_property("min-fresh", None, int) + only_if_cached: bool = cache_control_property("only-if-cached", None, bool) class ResponseCacheControl(_CacheControl): @@ -151,24 +218,55 @@ class ResponseCacheControl(_CacheControl): you plan to subclass it and add your own items have a look at the sourcecode for that class. + .. versionchanged:: 3.1 + Dict values are always ``str | None``. Setting properties will + convert the value to a string. Setting a non-bool property to + ``False`` is equivalent to setting it to ``None``. Getting typed + properties will return ``None`` if conversion raises + ``ValueError``, rather than the string. + + .. versionchanged:: 3.1 + ``no_cache`` is ``True`` if present without a value, rather than + ``"*"``. + + .. versionchanged:: 3.1 + ``private`` is ``True`` if present without a value, rather than + ``"*"``. + + .. versionchanged:: 3.1 + ``no_transform`` is a boolean. Previously it was mistakenly + always ``None``. + + .. versionchanged:: 3.1 + Added the ``must_understand``, ``stale_while_revalidate``, and + ``stale_if_error`` properties. + .. versionchanged:: 2.1.1 ``s_maxage`` converts the value to an int. - .. versionchanged:: 2.1.0 + .. versionchanged:: 2.1 Setting int properties such as ``max_age`` will convert the value to an int. .. versionadded:: 0.5 - In previous versions a `CacheControl` class existed that was used - both for request and response. + Request-only properties are not present on this response class. """ - public = cache_control_property("public", None, bool) - private = cache_control_property("private", "*", None) - must_revalidate = cache_control_property("must-revalidate", None, bool) - proxy_revalidate = cache_control_property("proxy-revalidate", None, bool) - s_maxage = cache_control_property("s-maxage", None, int) - immutable = cache_control_property("immutable", None, bool) + no_cache: str | t.Literal[True] | None = cache_control_property( + "no-cache", True, None + ) + public: bool = cache_control_property("public", None, bool) + private: str | t.Literal[True] | None = cache_control_property( + "private", True, None + ) + must_revalidate: bool = cache_control_property("must-revalidate", None, bool) + proxy_revalidate: bool = cache_control_property("proxy-revalidate", None, bool) + s_maxage: int | None = cache_control_property("s-maxage", None, int) + immutable: bool = cache_control_property("immutable", None, bool) + must_understand: bool = cache_control_property("must-understand", None, bool) + stale_while_revalidate: int | None = cache_control_property( + "stale-while-revalidate", None, int + ) # circular dependencies diff --git a/src/werkzeug/datastructures/cache_control.pyi b/src/werkzeug/datastructures/cache_control.pyi deleted file mode 100644 index 54ec020..0000000 --- a/src/werkzeug/datastructures/cache_control.pyi +++ /dev/null @@ -1,115 +0,0 @@ -from collections.abc import Callable -from collections.abc import Iterable -from collections.abc import Mapping -from typing import TypeVar - -from .mixins import ImmutableDictMixin -from .mixins import UpdateDictMixin - -T = TypeVar("T") -_CPT = TypeVar("_CPT", str, int, bool) - -def cache_control_property( - key: str, empty: _CPT | None, type: type[_CPT] -) -> property: ... - -class _CacheControl( - UpdateDictMixin[str, str | int | bool | None], dict[str, str | int | bool | None] -): - provided: bool - def __init__( - self, - values: Mapping[str, str | int | bool | None] - | Iterable[tuple[str, str | int | bool | None]] = (), - on_update: Callable[[_CacheControl], None] | None = None, - ) -> None: ... - @property - def no_cache(self) -> bool | None: ... - @no_cache.setter - def no_cache(self, value: bool | None) -> None: ... - @no_cache.deleter - def no_cache(self) -> None: ... - @property - def no_store(self) -> bool | None: ... - @no_store.setter - def no_store(self, value: bool | None) -> None: ... - @no_store.deleter - def no_store(self) -> None: ... - @property - def max_age(self) -> int | None: ... - @max_age.setter - def max_age(self, value: int | None) -> None: ... - @max_age.deleter - def max_age(self) -> None: ... - @property - def no_transform(self) -> bool | None: ... - @no_transform.setter - def no_transform(self, value: bool | None) -> None: ... - @no_transform.deleter - def no_transform(self) -> None: ... - def _get_cache_value(self, key: str, empty: T | None, type: type[T]) -> T: ... - def _set_cache_value(self, key: str, value: T | None, type: type[T]) -> None: ... - def _del_cache_value(self, key: str) -> None: ... - def to_header(self) -> str: ... - @staticmethod - def cache_property(key: str, empty: _CPT | None, type: type[_CPT]) -> property: ... - -class RequestCacheControl( # type: ignore[misc] - ImmutableDictMixin[str, str | int | bool | None], _CacheControl -): - @property - def max_stale(self) -> int | None: ... - @max_stale.setter - def max_stale(self, value: int | None) -> None: ... - @max_stale.deleter - def max_stale(self) -> None: ... - @property - def min_fresh(self) -> int | None: ... - @min_fresh.setter - def min_fresh(self, value: int | None) -> None: ... - @min_fresh.deleter - def min_fresh(self) -> None: ... - @property - def only_if_cached(self) -> bool | None: ... - @only_if_cached.setter - def only_if_cached(self, value: bool | None) -> None: ... - @only_if_cached.deleter - def only_if_cached(self) -> None: ... - -class ResponseCacheControl(_CacheControl): - @property - def public(self) -> bool | None: ... - @public.setter - def public(self, value: bool | None) -> None: ... - @public.deleter - def public(self) -> None: ... - @property - def private(self) -> bool | None: ... - @private.setter - def private(self, value: bool | None) -> None: ... - @private.deleter - def private(self) -> None: ... - @property - def must_revalidate(self) -> bool | None: ... - @must_revalidate.setter - def must_revalidate(self, value: bool | None) -> None: ... - @must_revalidate.deleter - def must_revalidate(self) -> None: ... - @property - def proxy_revalidate(self) -> bool | None: ... - @proxy_revalidate.setter - def proxy_revalidate(self, value: bool | None) -> None: ... - @proxy_revalidate.deleter - def proxy_revalidate(self) -> None: ... - @property - def s_maxage(self) -> int | None: ... - @s_maxage.setter - def s_maxage(self, value: int | None) -> None: ... - @s_maxage.deleter - def s_maxage(self) -> None: ... - @property - def immutable(self) -> bool | None: ... - @immutable.setter - def immutable(self, value: bool | None) -> None: ... - @immutable.deleter - def immutable(self) -> None: ... diff --git a/src/werkzeug/datastructures/csp.py b/src/werkzeug/datastructures/csp.py index dde9414..0353eeb 100644 --- a/src/werkzeug/datastructures/csp.py +++ b/src/werkzeug/datastructures/csp.py @@ -1,9 +1,12 @@ from __future__ import annotations -from .mixins import UpdateDictMixin +import collections.abc as cabc +import typing as t +from .structures import CallbackDict -def csp_property(key): + +def csp_property(key: str) -> t.Any: """Return a new property object for a content security policy header. Useful if you want to add support for a csp extension in a subclass. @@ -16,7 +19,7 @@ def csp_property(key): ) -class ContentSecurityPolicy(UpdateDictMixin, dict): +class ContentSecurityPolicy(CallbackDict[str, str]): """Subclass of a dict that stores values for a Content Security Policy header. It has accessors for all the level 3 policies. @@ -33,62 +36,65 @@ class ContentSecurityPolicy(UpdateDictMixin, dict): """ - base_uri = csp_property("base-uri") - child_src = csp_property("child-src") - connect_src = csp_property("connect-src") - default_src = csp_property("default-src") - font_src = csp_property("font-src") - form_action = csp_property("form-action") - frame_ancestors = csp_property("frame-ancestors") - frame_src = csp_property("frame-src") - img_src = csp_property("img-src") - manifest_src = csp_property("manifest-src") - media_src = csp_property("media-src") - navigate_to = csp_property("navigate-to") - object_src = csp_property("object-src") - prefetch_src = csp_property("prefetch-src") - plugin_types = csp_property("plugin-types") - report_to = csp_property("report-to") - report_uri = csp_property("report-uri") - sandbox = csp_property("sandbox") - script_src = csp_property("script-src") - script_src_attr = csp_property("script-src-attr") - script_src_elem = csp_property("script-src-elem") - style_src = csp_property("style-src") - style_src_attr = csp_property("style-src-attr") - style_src_elem = csp_property("style-src-elem") - worker_src = csp_property("worker-src") - - def __init__(self, values=(), on_update=None): - dict.__init__(self, values or ()) - self.on_update = on_update + base_uri: str | None = csp_property("base-uri") + child_src: str | None = csp_property("child-src") + connect_src: str | None = csp_property("connect-src") + default_src: str | None = csp_property("default-src") + font_src: str | None = csp_property("font-src") + form_action: str | None = csp_property("form-action") + frame_ancestors: str | None = csp_property("frame-ancestors") + frame_src: str | None = csp_property("frame-src") + img_src: str | None = csp_property("img-src") + manifest_src: str | None = csp_property("manifest-src") + media_src: str | None = csp_property("media-src") + navigate_to: str | None = csp_property("navigate-to") + object_src: str | None = csp_property("object-src") + prefetch_src: str | None = csp_property("prefetch-src") + plugin_types: str | None = csp_property("plugin-types") + report_to: str | None = csp_property("report-to") + report_uri: str | None = csp_property("report-uri") + sandbox: str | None = csp_property("sandbox") + script_src: str | None = csp_property("script-src") + script_src_attr: str | None = csp_property("script-src-attr") + script_src_elem: str | None = csp_property("script-src-elem") + style_src: str | None = csp_property("style-src") + style_src_attr: str | None = csp_property("style-src-attr") + style_src_elem: str | None = csp_property("style-src-elem") + worker_src: str | None = csp_property("worker-src") + + def __init__( + self, + values: cabc.Mapping[str, str] | cabc.Iterable[tuple[str, str]] | None = (), + on_update: cabc.Callable[[ContentSecurityPolicy], None] | None = None, + ) -> None: + super().__init__(values, on_update) self.provided = values is not None - def _get_value(self, key): + def _get_value(self, key: str) -> str | None: """Used internally by the accessor properties.""" return self.get(key) - def _set_value(self, key, value): + def _set_value(self, key: str, value: str | None) -> None: """Used internally by the accessor properties.""" if value is None: self.pop(key, None) else: self[key] = value - def _del_value(self, key): + def _del_value(self, key: str) -> None: """Used internally by the accessor properties.""" if key in self: del self[key] - def to_header(self): + def to_header(self) -> str: """Convert the stored values into a cache control header.""" from ..http import dump_csp_header return dump_csp_header(self) - def __str__(self): + def __str__(self) -> str: return self.to_header() - def __repr__(self): + def __repr__(self) -> str: kv_str = " ".join(f"{k}={v!r}" for k, v in sorted(self.items())) return f"<{type(self).__name__} {kv_str}>" diff --git a/src/werkzeug/datastructures/csp.pyi b/src/werkzeug/datastructures/csp.pyi deleted file mode 100644 index f9e2ac0..0000000 --- a/src/werkzeug/datastructures/csp.pyi +++ /dev/null @@ -1,169 +0,0 @@ -from collections.abc import Callable -from collections.abc import Iterable -from collections.abc import Mapping - -from .mixins import UpdateDictMixin - -def csp_property(key: str) -> property: ... - -class ContentSecurityPolicy(UpdateDictMixin[str, str], dict[str, str]): - @property - def base_uri(self) -> str | None: ... - @base_uri.setter - def base_uri(self, value: str | None) -> None: ... - @base_uri.deleter - def base_uri(self) -> None: ... - @property - def child_src(self) -> str | None: ... - @child_src.setter - def child_src(self, value: str | None) -> None: ... - @child_src.deleter - def child_src(self) -> None: ... - @property - def connect_src(self) -> str | None: ... - @connect_src.setter - def connect_src(self, value: str | None) -> None: ... - @connect_src.deleter - def connect_src(self) -> None: ... - @property - def default_src(self) -> str | None: ... - @default_src.setter - def default_src(self, value: str | None) -> None: ... - @default_src.deleter - def default_src(self) -> None: ... - @property - def font_src(self) -> str | None: ... - @font_src.setter - def font_src(self, value: str | None) -> None: ... - @font_src.deleter - def font_src(self) -> None: ... - @property - def form_action(self) -> str | None: ... - @form_action.setter - def form_action(self, value: str | None) -> None: ... - @form_action.deleter - def form_action(self) -> None: ... - @property - def frame_ancestors(self) -> str | None: ... - @frame_ancestors.setter - def frame_ancestors(self, value: str | None) -> None: ... - @frame_ancestors.deleter - def frame_ancestors(self) -> None: ... - @property - def frame_src(self) -> str | None: ... - @frame_src.setter - def frame_src(self, value: str | None) -> None: ... - @frame_src.deleter - def frame_src(self) -> None: ... - @property - def img_src(self) -> str | None: ... - @img_src.setter - def img_src(self, value: str | None) -> None: ... - @img_src.deleter - def img_src(self) -> None: ... - @property - def manifest_src(self) -> str | None: ... - @manifest_src.setter - def manifest_src(self, value: str | None) -> None: ... - @manifest_src.deleter - def manifest_src(self) -> None: ... - @property - def media_src(self) -> str | None: ... - @media_src.setter - def media_src(self, value: str | None) -> None: ... - @media_src.deleter - def media_src(self) -> None: ... - @property - def navigate_to(self) -> str | None: ... - @navigate_to.setter - def navigate_to(self, value: str | None) -> None: ... - @navigate_to.deleter - def navigate_to(self) -> None: ... - @property - def object_src(self) -> str | None: ... - @object_src.setter - def object_src(self, value: str | None) -> None: ... - @object_src.deleter - def object_src(self) -> None: ... - @property - def prefetch_src(self) -> str | None: ... - @prefetch_src.setter - def prefetch_src(self, value: str | None) -> None: ... - @prefetch_src.deleter - def prefetch_src(self) -> None: ... - @property - def plugin_types(self) -> str | None: ... - @plugin_types.setter - def plugin_types(self, value: str | None) -> None: ... - @plugin_types.deleter - def plugin_types(self) -> None: ... - @property - def report_to(self) -> str | None: ... - @report_to.setter - def report_to(self, value: str | None) -> None: ... - @report_to.deleter - def report_to(self) -> None: ... - @property - def report_uri(self) -> str | None: ... - @report_uri.setter - def report_uri(self, value: str | None) -> None: ... - @report_uri.deleter - def report_uri(self) -> None: ... - @property - def sandbox(self) -> str | None: ... - @sandbox.setter - def sandbox(self, value: str | None) -> None: ... - @sandbox.deleter - def sandbox(self) -> None: ... - @property - def script_src(self) -> str | None: ... - @script_src.setter - def script_src(self, value: str | None) -> None: ... - @script_src.deleter - def script_src(self) -> None: ... - @property - def script_src_attr(self) -> str | None: ... - @script_src_attr.setter - def script_src_attr(self, value: str | None) -> None: ... - @script_src_attr.deleter - def script_src_attr(self) -> None: ... - @property - def script_src_elem(self) -> str | None: ... - @script_src_elem.setter - def script_src_elem(self, value: str | None) -> None: ... - @script_src_elem.deleter - def script_src_elem(self) -> None: ... - @property - def style_src(self) -> str | None: ... - @style_src.setter - def style_src(self, value: str | None) -> None: ... - @style_src.deleter - def style_src(self) -> None: ... - @property - def style_src_attr(self) -> str | None: ... - @style_src_attr.setter - def style_src_attr(self, value: str | None) -> None: ... - @style_src_attr.deleter - def style_src_attr(self) -> None: ... - @property - def style_src_elem(self) -> str | None: ... - @style_src_elem.setter - def style_src_elem(self, value: str | None) -> None: ... - @style_src_elem.deleter - def style_src_elem(self) -> None: ... - @property - def worker_src(self) -> str | None: ... - @worker_src.setter - def worker_src(self, value: str | None) -> None: ... - @worker_src.deleter - def worker_src(self) -> None: ... - provided: bool - def __init__( - self, - values: Mapping[str, str] | Iterable[tuple[str, str]] = (), - on_update: Callable[[ContentSecurityPolicy], None] | None = None, - ) -> None: ... - def _get_value(self, key: str) -> str | None: ... - def _set_value(self, key: str, value: str) -> None: ... - def _del_value(self, key: str) -> None: ... - def to_header(self) -> str: ... diff --git a/src/werkzeug/datastructures/etag.py b/src/werkzeug/datastructures/etag.py index 747d996..a4ef342 100644 --- a/src/werkzeug/datastructures/etag.py +++ b/src/werkzeug/datastructures/etag.py @@ -1,14 +1,19 @@ from __future__ import annotations -from collections.abc import Collection +import collections.abc as cabc -class ETags(Collection): +class ETags(cabc.Collection[str]): """A set that can be used to check if one etag is present in a collection of etags. """ - def __init__(self, strong_etags=None, weak_etags=None, star_tag=False): + def __init__( + self, + strong_etags: cabc.Iterable[str] | None = None, + weak_etags: cabc.Iterable[str] | None = None, + star_tag: bool = False, + ): if not star_tag and strong_etags: self._strong = frozenset(strong_etags) else: @@ -17,7 +22,7 @@ def __init__(self, strong_etags=None, weak_etags=None, star_tag=False): self._weak = frozenset(weak_etags or ()) self.star_tag = star_tag - def as_set(self, include_weak=False): + def as_set(self, include_weak: bool = False) -> set[str]: """Convert the `ETags` object into a python set. Per default all the weak etags are not part of this set.""" rv = set(self._strong) @@ -25,19 +30,19 @@ def as_set(self, include_weak=False): rv.update(self._weak) return rv - def is_weak(self, etag): + def is_weak(self, etag: str) -> bool: """Check if an etag is weak.""" return etag in self._weak - def is_strong(self, etag): + def is_strong(self, etag: str) -> bool: """Check if an etag is strong.""" return etag in self._strong - def contains_weak(self, etag): + def contains_weak(self, etag: str) -> bool: """Check if an etag is part of the set including weak and strong tags.""" return self.is_weak(etag) or self.contains(etag) - def contains(self, etag): + def contains(self, etag: str) -> bool: """Check if an etag is part of the set ignoring weak tags. It is also possible to use the ``in`` operator. """ @@ -45,7 +50,7 @@ def contains(self, etag): return True return self.is_strong(etag) - def contains_raw(self, etag): + def contains_raw(self, etag: str) -> bool: """When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only.""" @@ -56,7 +61,7 @@ def contains_raw(self, etag): return self.contains_weak(etag) return self.contains(etag) - def to_header(self): + def to_header(self) -> str: """Convert the etags set into a HTTP header string.""" if self.star_tag: return "*" @@ -64,10 +69,16 @@ def to_header(self): [f'"{x}"' for x in self._strong] + [f'W/"{x}"' for x in self._weak] ) - def __call__(self, etag=None, data=None, include_weak=False): - if [etag, data].count(None) != 1: - raise TypeError("either tag or data required, but at least one") + def __call__( + self, + etag: str | None = None, + data: bytes | None = None, + include_weak: bool = False, + ) -> bool: if etag is None: + if data is None: + raise TypeError("'data' is required when 'etag' is not given.") + from ..http import generate_etag etag = generate_etag(data) @@ -76,20 +87,20 @@ def __call__(self, etag=None, data=None, include_weak=False): return True return etag in self._strong - def __bool__(self): + def __bool__(self) -> bool: return bool(self.star_tag or self._strong or self._weak) - def __str__(self): + def __str__(self) -> str: return self.to_header() - def __len__(self): + def __len__(self) -> int: return len(self._strong) - def __iter__(self): + def __iter__(self) -> cabc.Iterator[str]: return iter(self._strong) - def __contains__(self, etag): + def __contains__(self, etag: str) -> bool: # type: ignore[override] return self.contains(etag) - def __repr__(self): + def __repr__(self) -> str: return f"<{type(self).__name__} {str(self)!r}>" diff --git a/src/werkzeug/datastructures/etag.pyi b/src/werkzeug/datastructures/etag.pyi deleted file mode 100644 index 88e54f1..0000000 --- a/src/werkzeug/datastructures/etag.pyi +++ /dev/null @@ -1,30 +0,0 @@ -from collections.abc import Collection -from collections.abc import Iterable -from collections.abc import Iterator - -class ETags(Collection[str]): - _strong: frozenset[str] - _weak: frozenset[str] - star_tag: bool - def __init__( - self, - strong_etags: Iterable[str] | None = None, - weak_etags: Iterable[str] | None = None, - star_tag: bool = False, - ) -> None: ... - def as_set(self, include_weak: bool = False) -> set[str]: ... - def is_weak(self, etag: str) -> bool: ... - def is_strong(self, etag: str) -> bool: ... - def contains_weak(self, etag: str) -> bool: ... - def contains(self, etag: str) -> bool: ... - def contains_raw(self, etag: str) -> bool: ... - def to_header(self) -> str: ... - def __call__( - self, - etag: str | None = None, - data: bytes | None = None, - include_weak: bool = False, - ) -> bool: ... - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[str]: ... - def __contains__(self, item: str) -> bool: ... # type: ignore diff --git a/src/werkzeug/datastructures/file_storage.py b/src/werkzeug/datastructures/file_storage.py index e878a56..1234244 100644 --- a/src/werkzeug/datastructures/file_storage.py +++ b/src/werkzeug/datastructures/file_storage.py @@ -1,11 +1,15 @@ from __future__ import annotations +import collections.abc as cabc import mimetypes +import os +import typing as t from io import BytesIO from os import fsdecode from os import fspath from .._internal import _plain_int +from .headers import Headers from .structures import MultiDict @@ -19,12 +23,12 @@ class FileStorage: def __init__( self, - stream=None, - filename=None, - name=None, - content_type=None, - content_length=None, - headers=None, + stream: t.IO[bytes] | None = None, + filename: str | None = None, + name: str | None = None, + content_type: str | None = None, + content_length: int | None = None, + headers: Headers | None = None, ): self.name = name self.stream = stream or BytesIO() @@ -46,8 +50,6 @@ def __init__( self.filename = filename if headers is None: - from .headers import Headers - headers = Headers() self.headers = headers if content_type is not None: @@ -55,17 +57,17 @@ def __init__( if content_length is not None: headers["Content-Length"] = str(content_length) - def _parse_content_type(self): + def _parse_content_type(self) -> None: if not hasattr(self, "_parsed_content_type"): self._parsed_content_type = http.parse_options_header(self.content_type) @property - def content_type(self): + def content_type(self) -> str | None: """The content-type sent in the header. Usually not available""" return self.headers.get("content-type") @property - def content_length(self): + def content_length(self) -> int: """The content-length sent in the header. Usually not available""" if "content-length" in self.headers: try: @@ -76,7 +78,7 @@ def content_length(self): return 0 @property - def mimetype(self): + def mimetype(self) -> str: """Like :attr:`content_type`, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type is ``text/HTML; charset=utf-8`` the mimetype would be @@ -88,7 +90,7 @@ def mimetype(self): return self._parsed_content_type[0].lower() @property - def mimetype_params(self): + def mimetype_params(self) -> dict[str, str]: """The mimetype parameters as dict. For example if the content type is ``text/html; charset=utf-8`` the params would be ``{'charset': 'utf-8'}``. @@ -98,7 +100,9 @@ def mimetype_params(self): self._parse_content_type() return self._parsed_content_type[1] - def save(self, dst, buffer_size=16384): + def save( + self, dst: str | os.PathLike[str] | t.IO[bytes], buffer_size: int = 16384 + ) -> None: """Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during @@ -131,35 +135,34 @@ def save(self, dst, buffer_size=16384): if close_dst: dst.close() - def close(self): + def close(self) -> None: """Close the underlying file if possible.""" try: self.stream.close() except Exception: pass - def __bool__(self): + def __bool__(self) -> bool: return bool(self.filename) - def __getattr__(self, name): + def __getattr__(self, name: str) -> t.Any: try: return getattr(self.stream, name) except AttributeError: - # SpooledTemporaryFile doesn't implement IOBase, get the - # attribute from its backing file instead. - # https://github.com/python/cpython/pull/3249 + # SpooledTemporaryFile on Python < 3.11 doesn't implement IOBase, + # get the attribute from its backing file instead. if hasattr(self.stream, "_file"): return getattr(self.stream._file, name) raise - def __iter__(self): + def __iter__(self) -> cabc.Iterator[bytes]: return iter(self.stream) - def __repr__(self): + def __repr__(self) -> str: return f"<{type(self).__name__}: {self.filename!r} ({self.content_type!r})>" -class FileMultiDict(MultiDict): +class FileMultiDict(MultiDict[str, FileStorage]): """A special :class:`MultiDict` that has convenience methods to add files to it. This is used for :class:`EnvironBuilder` and generally useful for unittesting. @@ -167,7 +170,13 @@ class FileMultiDict(MultiDict): .. versionadded:: 0.5 """ - def add_file(self, name, file, filename=None, content_type=None): + def add_file( + self, + name: str, + file: str | os.PathLike[str] | t.IO[bytes] | FileStorage, + filename: str | None = None, + content_type: str | None = None, + ) -> None: """Adds a new file to the dict. `file` can be a file name or a :class:`file`-like or a :class:`FileStorage` object. @@ -177,19 +186,23 @@ def add_file(self, name, file, filename=None, content_type=None): :param content_type: an optional content type """ if isinstance(file, FileStorage): - value = file + self.add(name, file) + return + + if isinstance(file, (str, os.PathLike)): + if filename is None: + filename = os.fspath(file) + + file_obj: t.IO[bytes] = open(file, "rb") else: - if isinstance(file, str): - if filename is None: - filename = file - file = open(file, "rb") - if filename and content_type is None: - content_type = ( - mimetypes.guess_type(filename)[0] or "application/octet-stream" - ) - value = FileStorage(file, filename, name, content_type) - - self.add(name, value) + file_obj = file # type: ignore[assignment] + + if filename and content_type is None: + content_type = ( + mimetypes.guess_type(filename)[0] or "application/octet-stream" + ) + + self.add(name, FileStorage(file_obj, filename, name, content_type)) # circular dependencies diff --git a/src/werkzeug/datastructures/file_storage.pyi b/src/werkzeug/datastructures/file_storage.pyi deleted file mode 100644 index 36a7ed9..0000000 --- a/src/werkzeug/datastructures/file_storage.pyi +++ /dev/null @@ -1,49 +0,0 @@ -from collections.abc import Iterator -from os import PathLike -from typing import Any -from typing import IO - -from .headers import Headers -from .structures import MultiDict - -class FileStorage: - name: str | None - stream: IO[bytes] - filename: str | None - headers: Headers - _parsed_content_type: tuple[str, dict[str, str]] - def __init__( - self, - stream: IO[bytes] | None = None, - filename: str | PathLike[str] | None = None, - name: str | None = None, - content_type: str | None = None, - content_length: int | None = None, - headers: Headers | None = None, - ) -> None: ... - def _parse_content_type(self) -> None: ... - @property - def content_type(self) -> str: ... - @property - def content_length(self) -> int: ... - @property - def mimetype(self) -> str: ... - @property - def mimetype_params(self) -> dict[str, str]: ... - def save( - self, dst: str | PathLike[str] | IO[bytes], buffer_size: int = ... - ) -> None: ... - def close(self) -> None: ... - def __bool__(self) -> bool: ... - def __getattr__(self, name: str) -> Any: ... - def __iter__(self) -> Iterator[bytes]: ... - def __repr__(self) -> str: ... - -class FileMultiDict(MultiDict[str, FileStorage]): - def add_file( - self, - name: str, - file: FileStorage | str | IO[bytes], - filename: str | None = None, - content_type: str | None = None, - ) -> None: ... diff --git a/src/werkzeug/datastructures/headers.py b/src/werkzeug/datastructures/headers.py index d9dd655..1088e3b 100644 --- a/src/werkzeug/datastructures/headers.py +++ b/src/werkzeug/datastructures/headers.py @@ -1,5 +1,6 @@ from __future__ import annotations +import collections.abc as cabc import re import typing as t @@ -9,6 +10,12 @@ from .structures import iter_multi_items from .structures import MultiDict +if t.TYPE_CHECKING: + import typing_extensions as te + from _typeshed.wsgi import WSGIEnvironment + +T = t.TypeVar("T") + class Headers: """An object that stores some headers. It has a dict-like interface, @@ -34,6 +41,9 @@ class Headers: :param defaults: The list of default values for the :class:`Headers`. + .. versionchanged:: 3.1 + Implement ``|`` and ``|=`` operators. + .. versionchanged:: 2.1.0 Default values are validated the same as values added later. @@ -47,41 +57,72 @@ class Headers: was an API that does not support the changes to the encoding model. """ - def __init__(self, defaults=None): - self._list = [] + def __init__( + self, + defaults: ( + Headers + | MultiDict[str, t.Any] + | cabc.Mapping[str, t.Any | list[t.Any] | tuple[t.Any, ...] | set[t.Any]] + | cabc.Iterable[tuple[str, t.Any]] + | None + ) = None, + ) -> None: + self._list: list[tuple[str, str]] = [] + if defaults is not None: self.extend(defaults) - def __getitem__(self, key, _get_mode=False): - if not _get_mode: - if isinstance(key, int): - return self._list[key] - elif isinstance(key, slice): - return self.__class__(self._list[key]) - if not isinstance(key, str): - raise BadRequestKeyError(key) + @t.overload + def __getitem__(self, key: str) -> str: ... + @t.overload + def __getitem__(self, key: int) -> tuple[str, str]: ... + @t.overload + def __getitem__(self, key: slice) -> te.Self: ... + def __getitem__(self, key: str | int | slice) -> str | tuple[str, str] | te.Self: + if isinstance(key, str): + return self._get_key(key) + + if isinstance(key, int): + return self._list[key] + + return self.__class__(self._list[key]) + + def _get_key(self, key: str) -> str: ikey = key.lower() + for k, v in self._list: if k.lower() == ikey: return v - # micro optimization: if we are in get mode we will catch that - # exception one stack level down so we can raise a standard - # key error instead of our special one. - if _get_mode: - raise KeyError() - raise BadRequestKeyError(key) - def __eq__(self, other): - def lowered(item): - return (item[0].lower(),) + item[1:] - - return other.__class__ is self.__class__ and set( - map(lowered, other._list) - ) == set(map(lowered, self._list)) - - __hash__ = None + raise BadRequestKeyError(key) - def get(self, key, default=None, type=None): + def __eq__(self, other: object) -> bool: + if other.__class__ is not self.__class__: + return NotImplemented + + def lowered(item: tuple[str, ...]) -> tuple[str, ...]: + return item[0].lower(), *item[1:] + + return set(map(lowered, other._list)) == set(map(lowered, self._list)) # type: ignore[attr-defined] + + __hash__ = None # type: ignore[assignment] + + @t.overload + def get(self, key: str) -> str | None: ... + @t.overload + def get(self, key: str, default: str) -> str: ... + @t.overload + def get(self, key: str, default: T) -> str | T: ... + @t.overload + def get(self, key: str, type: cabc.Callable[[str], T]) -> T | None: ... + @t.overload + def get(self, key: str, default: T, type: cabc.Callable[[str], T]) -> T: ... + def get( # type: ignore[misc] + self, + key: str, + default: str | T | None = None, + type: cabc.Callable[[str], T] | None = None, + ) -> str | T | None: """Return the default value if the requested data doesn't exist. If `type` is provided and is a callable it should convert the value, return it or raise a :exc:`ValueError` if that is not possible. In @@ -107,17 +148,25 @@ def get(self, key, default=None, type=None): The ``as_bytes`` parameter was added. """ try: - rv = self.__getitem__(key, _get_mode=True) + rv = self._get_key(key) except KeyError: return default + if type is None: return rv + try: return type(rv) except ValueError: return default - def getlist(self, key, type=None): + @t.overload + def getlist(self, key: str) -> list[str]: ... + @t.overload + def getlist(self, key: str, type: cabc.Callable[[str], T]) -> list[T]: ... + def getlist( + self, key: str, type: cabc.Callable[[str], T] | None = None + ) -> list[str] | list[T]: """Return the list of items for a given key. If that key is not in the :class:`Headers`, the return value will be an empty list. Just like :meth:`get`, :meth:`getlist` accepts a `type` parameter. All items will @@ -136,18 +185,22 @@ def getlist(self, key, type=None): The ``as_bytes`` parameter was added. """ ikey = key.lower() - result = [] - for k, v in self: - if k.lower() == ikey: - if type is not None: + + if type is not None: + result = [] + + for k, v in self: + if k.lower() == ikey: try: - v = type(v) + result.append(type(v)) except ValueError: continue - result.append(v) - return result - def get_all(self, name): + return result + + return [v for k, v in self if k.lower() == ikey] + + def get_all(self, name: str) -> list[str]: """Return a list of all the values for the named field. This method is compatible with the :mod:`wsgiref` @@ -155,21 +208,32 @@ def get_all(self, name): """ return self.getlist(name) - def items(self, lower=False): + def items(self, lower: bool = False) -> t.Iterable[tuple[str, str]]: for key, value in self: if lower: key = key.lower() yield key, value - def keys(self, lower=False): + def keys(self, lower: bool = False) -> t.Iterable[str]: for key, _ in self.items(lower): yield key - def values(self): + def values(self) -> t.Iterable[str]: for _, value in self.items(): yield value - def extend(self, *args, **kwargs): + def extend( + self, + arg: ( + Headers + | MultiDict[str, t.Any] + | cabc.Mapping[str, t.Any | list[t.Any] | tuple[t.Any, ...] | set[t.Any]] + | cabc.Iterable[tuple[str, t.Any]] + | None + ) = None, + /, + **kwargs: str, + ) -> None: """Extend headers in this object with items from another object containing header items as well as keyword arguments. @@ -183,35 +247,52 @@ def extend(self, *args, **kwargs): .. versionchanged:: 1.0 Support :class:`MultiDict`. Allow passing ``kwargs``. """ - if len(args) > 1: - raise TypeError(f"update expected at most 1 arguments, got {len(args)}") - - if args: - for key, value in iter_multi_items(args[0]): + if arg is not None: + for key, value in iter_multi_items(arg): self.add(key, value) for key, value in iter_multi_items(kwargs): self.add(key, value) - def __delitem__(self, key, _index_operation=True): - if _index_operation and isinstance(key, (int, slice)): - del self._list[key] + def __delitem__(self, key: str | int | slice) -> None: + if isinstance(key, str): + self._del_key(key) return + + del self._list[key] + + def _del_key(self, key: str) -> None: key = key.lower() new = [] + for k, v in self._list: if k.lower() != key: new.append((k, v)) + self._list[:] = new - def remove(self, key): + def remove(self, key: str) -> None: """Remove a key. :param key: The key to be removed. """ - return self.__delitem__(key, _index_operation=False) - - def pop(self, key=None, default=_missing): + return self._del_key(key) + + @t.overload + def pop(self) -> tuple[str, str]: ... + @t.overload + def pop(self, key: str) -> str: ... + @t.overload + def pop(self, key: int | None = ...) -> tuple[str, str]: ... + @t.overload + def pop(self, key: str, default: str) -> str: ... + @t.overload + def pop(self, key: str, default: T) -> str | T: ... + def pop( + self, + key: str | int | None = None, + default: str | T = _missing, # type: ignore[assignment] + ) -> str | tuple[str, str] | T: """Removes and returns a key or index. :param key: The key to be popped. If this is an integer the item at @@ -222,37 +303,42 @@ def pop(self, key=None, default=_missing): """ if key is None: return self._list.pop() + if isinstance(key, int): return self._list.pop(key) + try: - rv = self[key] - self.remove(key) + rv = self._get_key(key) except KeyError: if default is not _missing: return default + raise + + self.remove(key) return rv - def popitem(self): + def popitem(self) -> tuple[str, str]: """Removes a key or index and returns a (key, value) item.""" - return self.pop() + return self._list.pop() - def __contains__(self, key): + def __contains__(self, key: str) -> bool: """Check if a key is present.""" try: - self.__getitem__(key, _get_mode=True) + self._get_key(key) except KeyError: return False + return True - def __iter__(self): + def __iter__(self) -> t.Iterator[tuple[str, str]]: """Yield ``(key, value)`` tuples.""" return iter(self._list) - def __len__(self): + def __len__(self) -> int: return len(self._list) - def add(self, _key, _value, **kw): + def add(self, key: str, value: t.Any, /, **kwargs: t.Any) -> None: """Add a new header tuple to the list. Keyword arguments can specify additional parameters for the header @@ -265,27 +351,28 @@ def add(self, _key, _value, **kw): The keyword argument dumping uses :func:`dump_options_header` behind the scenes. - .. versionadded:: 0.4.1 + .. versionchanged:: 0.4.1 keyword arguments were added for :mod:`wsgiref` compatibility. """ - if kw: - _value = _options_header_vkw(_value, kw) - _value = _str_header_value(_value) - self._list.append((_key, _value)) + if kwargs: + value = _options_header_vkw(value, kwargs) - def add_header(self, _key, _value, **_kw): + value_str = _str_header_value(value) + self._list.append((key, value_str)) + + def add_header(self, key: str, value: t.Any, /, **kwargs: t.Any) -> None: """Add a new header tuple to the list. An alias for :meth:`add` for compatibility with the :mod:`wsgiref` :meth:`~wsgiref.headers.Headers.add_header` method. """ - self.add(_key, _value, **_kw) + self.add(key, value, **kwargs) - def clear(self): + def clear(self) -> None: """Clears all headers.""" - del self._list[:] + self._list.clear() - def set(self, _key, _value, **kw): + def set(self, key: str, value: t.Any, /, **kwargs: t.Any) -> None: """Remove all header tuples for `key` and add a new one. The newly added key either appears at the end of the list if there was no entry or replaces the first one. @@ -300,25 +387,32 @@ def set(self, _key, _value, **kw): :param key: The key to be inserted. :param value: The value to be inserted. """ - if kw: - _value = _options_header_vkw(_value, kw) - _value = _str_header_value(_value) + if kwargs: + value = _options_header_vkw(value, kwargs) + + value_str = _str_header_value(value) + if not self._list: - self._list.append((_key, _value)) + self._list.append((key, value_str)) return - listiter = iter(self._list) - ikey = _key.lower() - for idx, (old_key, _old_value) in enumerate(listiter): + + iter_list = iter(self._list) + ikey = key.lower() + + for idx, (old_key, _) in enumerate(iter_list): if old_key.lower() == ikey: # replace first occurrence - self._list[idx] = (_key, _value) + self._list[idx] = (key, value_str) break else: - self._list.append((_key, _value)) + # no existing occurrences + self._list.append((key, value_str)) return - self._list[idx + 1 :] = [t for t in listiter if t[0].lower() != ikey] - def setlist(self, key, values): + # remove remaining occurrences + self._list[idx + 1 :] = [t for t in iter_list if t[0].lower() != ikey] + + def setlist(self, key: str, values: cabc.Iterable[t.Any]) -> None: """Remove any existing values for a header and add new ones. :param key: The header key to set. @@ -335,7 +429,7 @@ def setlist(self, key, values): else: self.remove(key) - def setdefault(self, key, default): + def setdefault(self, key: str, default: t.Any) -> str: """Return the first value for the key if it is in the headers, otherwise set the header to the value given by ``default`` and return that. @@ -344,13 +438,15 @@ def setdefault(self, key, default): :param default: The value to set for the key if it is not in the headers. """ - if key in self: - return self[key] + try: + return self._get_key(key) + except KeyError: + pass self.set(key, default) - return default + return self._get_key(key) - def setlistdefault(self, key, default): + def setlistdefault(self, key: str, default: cabc.Iterable[t.Any]) -> list[str]: """Return the list of values for the key if it is in the headers, otherwise set the header to the list of values given by ``default`` and return that. @@ -369,20 +465,41 @@ def setlistdefault(self, key, default): return self.getlist(key) - def __setitem__(self, key, value): + @t.overload + def __setitem__(self, key: str, value: t.Any) -> None: ... + @t.overload + def __setitem__(self, key: int, value: tuple[str, t.Any]) -> None: ... + @t.overload + def __setitem__( + self, key: slice, value: cabc.Iterable[tuple[str, t.Any]] + ) -> None: ... + def __setitem__( + self, + key: str | int | slice, + value: t.Any | tuple[str, t.Any] | cabc.Iterable[tuple[str, t.Any]], + ) -> None: """Like :meth:`set` but also supports index/slice based setting.""" - if isinstance(key, (slice, int)): - if isinstance(key, int): - value = [value] - value = [(k, _str_header_value(v)) for (k, v) in value] - if isinstance(key, int): - self._list[key] = value[0] - else: - self._list[key] = value - else: + if isinstance(key, str): self.set(key, value) - - def update(self, *args, **kwargs): + elif isinstance(key, int): + self._list[key] = value[0], _str_header_value(value[1]) # type: ignore[index] + else: + self._list[key] = [(k, _str_header_value(v)) for k, v in value] # type: ignore[misc] + + def update( + self, + arg: ( + Headers + | MultiDict[str, t.Any] + | cabc.Mapping[ + str, t.Any | list[t.Any] | tuple[t.Any, ...] | cabc.Set[t.Any] + ] + | cabc.Iterable[tuple[str, t.Any]] + | None + ) = None, + /, + **kwargs: t.Any | list[t.Any] | tuple[t.Any, ...] | cabc.Set[t.Any], + ) -> None: """Replace headers in this object with items from another headers object and keyword arguments. @@ -395,45 +512,66 @@ def update(self, *args, **kwargs): .. versionadded:: 1.0 """ - if len(args) > 1: - raise TypeError(f"update expected at most 1 arguments, got {len(args)}") - - if args: - mapping = args[0] - - if isinstance(mapping, (Headers, MultiDict)): - for key in mapping.keys(): - self.setlist(key, mapping.getlist(key)) - elif isinstance(mapping, dict): - for key, value in mapping.items(): - if isinstance(value, (list, tuple)): + if arg is not None: + if isinstance(arg, (Headers, MultiDict)): + for key in arg.keys(): + self.setlist(key, arg.getlist(key)) + elif isinstance(arg, cabc.Mapping): + for key, value in arg.items(): + if isinstance(value, (list, tuple, set)): self.setlist(key, value) else: self.set(key, value) else: - for key, value in mapping: + for key, value in arg: self.set(key, value) for key, value in kwargs.items(): - if isinstance(value, (list, tuple)): + if isinstance(value, (list, tuple, set)): self.setlist(key, value) else: self.set(key, value) - def to_wsgi_list(self): + def __or__( + self, + other: cabc.Mapping[ + str, t.Any | list[t.Any] | tuple[t.Any, ...] | cabc.Set[t.Any] + ], + ) -> te.Self: + if not isinstance(other, cabc.Mapping): + return NotImplemented + + rv = self.copy() + rv.update(other) + return rv + + def __ior__( + self, + other: ( + cabc.Mapping[str, t.Any | list[t.Any] | tuple[t.Any, ...] | cabc.Set[t.Any]] + | cabc.Iterable[tuple[str, t.Any]] + ), + ) -> te.Self: + if not isinstance(other, (cabc.Mapping, cabc.Iterable)): + return NotImplemented + + self.update(other) + return self + + def to_wsgi_list(self) -> list[tuple[str, str]]: """Convert the headers into a list suitable for WSGI. :return: list """ return list(self) - def copy(self): + def copy(self) -> te.Self: return self.__class__(self._list) - def __copy__(self): + def __copy__(self) -> te.Self: return self.copy() - def __str__(self): + def __str__(self) -> str: """Returns formatted headers suitable for HTTP transmission.""" strs = [] for key, value in self.to_wsgi_list(): @@ -441,11 +579,11 @@ def __str__(self): strs.append("\r\n") return "\r\n".join(strs) - def __repr__(self): + def __repr__(self) -> str: return f"{type(self).__name__}({list(self)!r})" -def _options_header_vkw(value: str, kw: dict[str, t.Any]): +def _options_header_vkw(value: str, kw: dict[str, t.Any]) -> str: return http.dump_options_header( value, {k.replace("_", "-"): v for k, v in kw.items()} ) @@ -461,10 +599,10 @@ def _str_header_value(value: t.Any) -> str: if _newline_re.search(value) is not None: raise ValueError("Header values must not contain newline characters.") - return value + return value # type: ignore[no-any-return] -class EnvironHeaders(ImmutableHeadersMixin, Headers): +class EnvironHeaders(ImmutableHeadersMixin, Headers): # type: ignore[misc] """Read only version of the headers from a WSGI environment. This provides the same interface as `Headers` and is constructed from a WSGI environment. @@ -474,30 +612,36 @@ class EnvironHeaders(ImmutableHeadersMixin, Headers): HTTP exceptions. """ - def __init__(self, environ): + def __init__(self, environ: WSGIEnvironment) -> None: + super().__init__() self.environ = environ - def __eq__(self, other): + def __eq__(self, other: object) -> bool: + if not isinstance(other, EnvironHeaders): + return NotImplemented + return self.environ is other.environ - __hash__ = None + __hash__ = None # type: ignore[assignment] - def __getitem__(self, key, _get_mode=False): - # _get_mode is a no-op for this class as there is no index but - # used because get() calls it. + def __getitem__(self, key: str) -> str: # type: ignore[override] + return self._get_key(key) + + def _get_key(self, key: str) -> str: if not isinstance(key, str): - raise KeyError(key) + raise BadRequestKeyError(key) + key = key.upper().replace("-", "_") + if key in {"CONTENT_TYPE", "CONTENT_LENGTH"}: - return self.environ[key] - return self.environ[f"HTTP_{key}"] + return self.environ[key] # type: ignore[no-any-return] - def __len__(self): - # the iter is necessary because otherwise list calls our - # len which would call list again and so forth. - return len(list(iter(self))) + return self.environ[f"HTTP_{key}"] # type: ignore[no-any-return] - def __iter__(self): + def __len__(self) -> int: + return sum(1 for _ in self) + + def __iter__(self) -> cabc.Iterator[tuple[str, str]]: for key, value in self.environ.items(): if key.startswith("HTTP_") and key not in { "HTTP_CONTENT_TYPE", @@ -507,7 +651,10 @@ def __iter__(self): elif key in {"CONTENT_TYPE", "CONTENT_LENGTH"} and value: yield key.replace("_", "-").title(), value - def copy(self): + def copy(self) -> t.NoReturn: + raise TypeError(f"cannot create {type(self).__name__!r} copies") + + def __or__(self, other: t.Any) -> t.NoReturn: raise TypeError(f"cannot create {type(self).__name__!r} copies") diff --git a/src/werkzeug/datastructures/headers.pyi b/src/werkzeug/datastructures/headers.pyi deleted file mode 100644 index 8650222..0000000 --- a/src/werkzeug/datastructures/headers.pyi +++ /dev/null @@ -1,109 +0,0 @@ -from collections.abc import Callable -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import Mapping -from typing import Literal -from typing import NoReturn -from typing import overload -from typing import TypeVar - -from _typeshed import SupportsKeysAndGetItem -from _typeshed.wsgi import WSGIEnvironment - -from .mixins import ImmutableHeadersMixin - -D = TypeVar("D") -T = TypeVar("T") - -class Headers(dict[str, str]): - _list: list[tuple[str, str]] - def __init__( - self, - defaults: Mapping[str, str | Iterable[str]] - | Iterable[tuple[str, str]] - | None = None, - ) -> None: ... - @overload - def __getitem__(self, key: str) -> str: ... - @overload - def __getitem__(self, key: int) -> tuple[str, str]: ... - @overload - def __getitem__(self, key: slice) -> Headers: ... - @overload - def __getitem__(self, key: str, _get_mode: Literal[True] = ...) -> str: ... - def __eq__(self, other: object) -> bool: ... - @overload # type: ignore - def get(self, key: str, default: str) -> str: ... - @overload - def get(self, key: str, default: str | None = None) -> str | None: ... - @overload - def get( - self, key: str, default: T | None = None, type: Callable[[str], T] = ... - ) -> T | None: ... - @overload - def getlist(self, key: str) -> list[str]: ... - @overload - def getlist(self, key: str, type: Callable[[str], T]) -> list[T]: ... - def get_all(self, name: str) -> list[str]: ... - def items( # type: ignore - self, lower: bool = False - ) -> Iterator[tuple[str, str]]: ... - def keys(self, lower: bool = False) -> Iterator[str]: ... # type: ignore - def values(self) -> Iterator[str]: ... # type: ignore - def extend( - self, - *args: Mapping[str, str | Iterable[str]] | Iterable[tuple[str, str]], - **kwargs: str | Iterable[str], - ) -> None: ... - @overload - def __delitem__(self, key: str | int | slice) -> None: ... - @overload - def __delitem__(self, key: str, _index_operation: Literal[False]) -> None: ... - def remove(self, key: str) -> None: ... - @overload # type: ignore - def pop(self, key: str, default: str | None = None) -> str: ... - @overload - def pop( - self, key: int | None = None, default: tuple[str, str] | None = None - ) -> tuple[str, str]: ... - def popitem(self) -> tuple[str, str]: ... - def __contains__(self, key: str) -> bool: ... # type: ignore - def has_key(self, key: str) -> bool: ... - def __iter__(self) -> Iterator[tuple[str, str]]: ... # type: ignore - def add(self, _key: str, _value: str, **kw: str) -> None: ... - def _validate_value(self, value: str) -> None: ... - def add_header(self, _key: str, _value: str, **_kw: str) -> None: ... - def clear(self) -> None: ... - def set(self, _key: str, _value: str, **kw: str) -> None: ... - def setlist(self, key: str, values: Iterable[str]) -> None: ... - def setdefault(self, key: str, default: str) -> str: ... - def setlistdefault(self, key: str, default: Iterable[str]) -> None: ... - @overload - def __setitem__(self, key: str, value: str) -> None: ... - @overload - def __setitem__(self, key: int, value: tuple[str, str]) -> None: ... - @overload - def __setitem__(self, key: slice, value: Iterable[tuple[str, str]]) -> None: ... - @overload - def update( - self, __m: SupportsKeysAndGetItem[str, str], **kwargs: str | Iterable[str] - ) -> None: ... - @overload - def update( - self, __m: Iterable[tuple[str, str]], **kwargs: str | Iterable[str] - ) -> None: ... - @overload - def update(self, **kwargs: str | Iterable[str]) -> None: ... - def to_wsgi_list(self) -> list[tuple[str, str]]: ... - def copy(self) -> Headers: ... - def __copy__(self) -> Headers: ... - -class EnvironHeaders(ImmutableHeadersMixin, Headers): - environ: WSGIEnvironment - def __init__(self, environ: WSGIEnvironment) -> None: ... - def __eq__(self, other: object) -> bool: ... - def __getitem__( # type: ignore - self, key: str, _get_mode: Literal[False] = False - ) -> str: ... - def __iter__(self) -> Iterator[tuple[str, str]]: ... # type: ignore - def copy(self) -> NoReturn: ... diff --git a/src/werkzeug/datastructures/mixins.py b/src/werkzeug/datastructures/mixins.py index 2c84ca8..03d461a 100644 --- a/src/werkzeug/datastructures/mixins.py +++ b/src/werkzeug/datastructures/mixins.py @@ -1,11 +1,22 @@ from __future__ import annotations +import collections.abc as cabc +import typing as t +from functools import update_wrapper from itertools import repeat from .._internal import _missing +if t.TYPE_CHECKING: + import typing_extensions as te -def is_immutable(self): +K = t.TypeVar("K") +V = t.TypeVar("V") +T = t.TypeVar("T") +F = t.TypeVar("F", bound=cabc.Callable[..., t.Any]) + + +def _immutable_error(self: t.Any) -> t.NoReturn: raise TypeError(f"{type(self).__name__!r} objects are immutable") @@ -17,102 +28,118 @@ class ImmutableListMixin: :private: """ - _hash_cache = None + _hash_cache: int | None = None - def __hash__(self): + def __hash__(self) -> int: if self._hash_cache is not None: return self._hash_cache - rv = self._hash_cache = hash(tuple(self)) + rv = self._hash_cache = hash(tuple(self)) # type: ignore[arg-type] return rv - def __reduce_ex__(self, protocol): - return type(self), (list(self),) + def __reduce_ex__(self, protocol: t.SupportsIndex) -> t.Any: + return type(self), (list(self),) # type: ignore[call-overload] - def __delitem__(self, key): - is_immutable(self) + def __delitem__(self, key: t.Any) -> t.NoReturn: + _immutable_error(self) - def __iadd__(self, other): - is_immutable(self) + def __iadd__(self, other: t.Any) -> t.NoReturn: + _immutable_error(self) - def __imul__(self, other): - is_immutable(self) + def __imul__(self, other: t.Any) -> t.NoReturn: + _immutable_error(self) - def __setitem__(self, key, value): - is_immutable(self) + def __setitem__(self, key: t.Any, value: t.Any) -> t.NoReturn: + _immutable_error(self) - def append(self, item): - is_immutable(self) + def append(self, item: t.Any) -> t.NoReturn: + _immutable_error(self) - def remove(self, item): - is_immutable(self) + def remove(self, item: t.Any) -> t.NoReturn: + _immutable_error(self) - def extend(self, iterable): - is_immutable(self) + def extend(self, iterable: t.Any) -> t.NoReturn: + _immutable_error(self) - def insert(self, pos, value): - is_immutable(self) + def insert(self, pos: t.Any, value: t.Any) -> t.NoReturn: + _immutable_error(self) - def pop(self, index=-1): - is_immutable(self) + def pop(self, index: t.Any = -1) -> t.NoReturn: + _immutable_error(self) - def reverse(self): - is_immutable(self) + def reverse(self: t.Any) -> t.NoReturn: + _immutable_error(self) - def sort(self, key=None, reverse=False): - is_immutable(self) + def sort(self, key: t.Any = None, reverse: t.Any = False) -> t.NoReturn: + _immutable_error(self) -class ImmutableDictMixin: +class ImmutableDictMixin(t.Generic[K, V]): """Makes a :class:`dict` immutable. + .. versionchanged:: 3.1 + Disallow ``|=`` operator. + .. versionadded:: 0.5 :private: """ - _hash_cache = None + _hash_cache: int | None = None @classmethod - def fromkeys(cls, keys, value=None): + @t.overload + def fromkeys( + cls, keys: cabc.Iterable[K], value: None + ) -> ImmutableDictMixin[K, t.Any | None]: ... + @classmethod + @t.overload + def fromkeys(cls, keys: cabc.Iterable[K], value: V) -> ImmutableDictMixin[K, V]: ... + @classmethod + def fromkeys( + cls, keys: cabc.Iterable[K], value: V | None = None + ) -> ImmutableDictMixin[K, t.Any | None] | ImmutableDictMixin[K, V]: instance = super().__new__(cls) - instance.__init__(zip(keys, repeat(value))) + instance.__init__(zip(keys, repeat(value))) # type: ignore[misc] return instance - def __reduce_ex__(self, protocol): - return type(self), (dict(self),) + def __reduce_ex__(self, protocol: t.SupportsIndex) -> t.Any: + return type(self), (dict(self),) # type: ignore[call-overload] - def _iter_hashitems(self): - return self.items() + def _iter_hashitems(self) -> t.Iterable[t.Any]: + return self.items() # type: ignore[attr-defined,no-any-return] - def __hash__(self): + def __hash__(self) -> int: if self._hash_cache is not None: return self._hash_cache rv = self._hash_cache = hash(frozenset(self._iter_hashitems())) return rv - def setdefault(self, key, default=None): - is_immutable(self) + def setdefault(self, key: t.Any, default: t.Any = None) -> t.NoReturn: + _immutable_error(self) + + def update(self, arg: t.Any, /, **kwargs: t.Any) -> t.NoReturn: + _immutable_error(self) - def update(self, *args, **kwargs): - is_immutable(self) + def __ior__(self, other: t.Any) -> t.NoReturn: + _immutable_error(self) - def pop(self, key, default=None): - is_immutable(self) + def pop(self, key: t.Any, default: t.Any = None) -> t.NoReturn: + _immutable_error(self) - def popitem(self): - is_immutable(self) + def popitem(self) -> t.NoReturn: + _immutable_error(self) - def __setitem__(self, key, value): - is_immutable(self) + def __setitem__(self, key: t.Any, value: t.Any) -> t.NoReturn: + _immutable_error(self) - def __delitem__(self, key): - is_immutable(self) + def __delitem__(self, key: t.Any) -> t.NoReturn: + _immutable_error(self) - def clear(self): - is_immutable(self) + def clear(self) -> t.NoReturn: + _immutable_error(self) -class ImmutableMultiDictMixin(ImmutableDictMixin): +class ImmutableMultiDictMixin(ImmutableDictMixin[K, V]): """Makes a :class:`MultiDict` immutable. .. versionadded:: 0.5 @@ -120,26 +147,26 @@ class ImmutableMultiDictMixin(ImmutableDictMixin): :private: """ - def __reduce_ex__(self, protocol): - return type(self), (list(self.items(multi=True)),) + def __reduce_ex__(self, protocol: t.SupportsIndex) -> t.Any: + return type(self), (list(self.items(multi=True)),) # type: ignore[attr-defined] - def _iter_hashitems(self): - return self.items(multi=True) + def _iter_hashitems(self) -> t.Iterable[t.Any]: + return self.items(multi=True) # type: ignore[attr-defined,no-any-return] - def add(self, key, value): - is_immutable(self) + def add(self, key: t.Any, value: t.Any) -> t.NoReturn: + _immutable_error(self) - def popitemlist(self): - is_immutable(self) + def popitemlist(self) -> t.NoReturn: + _immutable_error(self) - def poplist(self, key): - is_immutable(self) + def poplist(self, key: t.Any) -> t.NoReturn: + _immutable_error(self) - def setlist(self, key, new_list): - is_immutable(self) + def setlist(self, key: t.Any, new_list: t.Any) -> t.NoReturn: + _immutable_error(self) - def setlistdefault(self, key, default_list=None): - is_immutable(self) + def setlistdefault(self, key: t.Any, default_list: t.Any = None) -> t.NoReturn: + _immutable_error(self) class ImmutableHeadersMixin: @@ -147,96 +174,144 @@ class ImmutableHeadersMixin: hashable though since the only usecase for this datastructure in Werkzeug is a view on a mutable structure. + .. versionchanged:: 3.1 + Disallow ``|=`` operator. + .. versionadded:: 0.5 :private: """ - def __delitem__(self, key, **kwargs): - is_immutable(self) + def __delitem__(self, key: t.Any, **kwargs: t.Any) -> t.NoReturn: + _immutable_error(self) + + def __setitem__(self, key: t.Any, value: t.Any) -> t.NoReturn: + _immutable_error(self) - def __setitem__(self, key, value): - is_immutable(self) + def set(self, key: t.Any, value: t.Any, /, **kwargs: t.Any) -> t.NoReturn: + _immutable_error(self) - def set(self, _key, _value, **kwargs): - is_immutable(self) + def setlist(self, key: t.Any, values: t.Any) -> t.NoReturn: + _immutable_error(self) - def setlist(self, key, values): - is_immutable(self) + def add(self, key: t.Any, value: t.Any, /, **kwargs: t.Any) -> t.NoReturn: + _immutable_error(self) - def add(self, _key, _value, **kwargs): - is_immutable(self) + def add_header(self, key: t.Any, value: t.Any, /, **kwargs: t.Any) -> t.NoReturn: + _immutable_error(self) - def add_header(self, _key, _value, **_kwargs): - is_immutable(self) + def remove(self, key: t.Any) -> t.NoReturn: + _immutable_error(self) - def remove(self, key): - is_immutable(self) + def extend(self, arg: t.Any, /, **kwargs: t.Any) -> t.NoReturn: + _immutable_error(self) - def extend(self, *args, **kwargs): - is_immutable(self) + def update(self, arg: t.Any, /, **kwargs: t.Any) -> t.NoReturn: + _immutable_error(self) - def update(self, *args, **kwargs): - is_immutable(self) + def __ior__(self, other: t.Any) -> t.NoReturn: + _immutable_error(self) - def insert(self, pos, value): - is_immutable(self) + def insert(self, pos: t.Any, value: t.Any) -> t.NoReturn: + _immutable_error(self) - def pop(self, key=None, default=_missing): - is_immutable(self) + def pop(self, key: t.Any = None, default: t.Any = _missing) -> t.NoReturn: + _immutable_error(self) - def popitem(self): - is_immutable(self) + def popitem(self) -> t.NoReturn: + _immutable_error(self) - def setdefault(self, key, default): - is_immutable(self) + def setdefault(self, key: t.Any, default: t.Any) -> t.NoReturn: + _immutable_error(self) - def setlistdefault(self, key, default): - is_immutable(self) + def setlistdefault(self, key: t.Any, default: t.Any) -> t.NoReturn: + _immutable_error(self) -def _calls_update(name): - def oncall(self, *args, **kw): - rv = getattr(super(UpdateDictMixin, self), name)(*args, **kw) +def _always_update(f: F) -> F: + def wrapper( + self: UpdateDictMixin[t.Any, t.Any], /, *args: t.Any, **kwargs: t.Any + ) -> t.Any: + rv = f(self, *args, **kwargs) if self.on_update is not None: self.on_update(self) return rv - oncall.__name__ = name - return oncall + return update_wrapper(wrapper, f) # type: ignore[return-value] -class UpdateDictMixin(dict): +class UpdateDictMixin(dict[K, V]): """Makes dicts call `self.on_update` on modifications. + .. versionchanged:: 3.1 + Implement ``|=`` operator. + .. versionadded:: 0.5 :private: """ - on_update = None + on_update: cabc.Callable[[te.Self], None] | None = None - def setdefault(self, key, default=None): + def setdefault(self: te.Self, key: K, default: V | None = None) -> V: modified = key not in self - rv = super().setdefault(key, default) + rv = super().setdefault(key, default) # type: ignore[arg-type] if modified and self.on_update is not None: self.on_update(self) return rv - def pop(self, key, default=_missing): + @t.overload + def pop(self: te.Self, key: K) -> V: ... + @t.overload + def pop(self: te.Self, key: K, default: V) -> V: ... + @t.overload + def pop(self: te.Self, key: K, default: T) -> T: ... + def pop( + self: te.Self, + key: K, + default: V | T = _missing, # type: ignore[assignment] + ) -> V | T: modified = key in self if default is _missing: rv = super().pop(key) else: - rv = super().pop(key, default) + rv = super().pop(key, default) # type: ignore[arg-type] if modified and self.on_update is not None: self.on_update(self) return rv - __setitem__ = _calls_update("__setitem__") - __delitem__ = _calls_update("__delitem__") - clear = _calls_update("clear") - popitem = _calls_update("popitem") - update = _calls_update("update") + @_always_update + def __setitem__(self, key: K, value: V) -> None: + super().__setitem__(key, value) + + @_always_update + def __delitem__(self, key: K) -> None: + super().__delitem__(key) + + @_always_update + def clear(self) -> None: + super().clear() + + @_always_update + def popitem(self) -> tuple[K, V]: + return super().popitem() + + @_always_update + def update( # type: ignore[override] + self, + arg: cabc.Mapping[K, V] | cabc.Iterable[tuple[K, V]] | None = None, + /, + **kwargs: V, + ) -> None: + if arg is None: + super().update(**kwargs) + else: + super().update(arg, **kwargs) + + @_always_update + def __ior__( # type: ignore[override] + self, other: cabc.Mapping[K, V] | cabc.Iterable[tuple[K, V]] + ) -> te.Self: + return super().__ior__(other) diff --git a/src/werkzeug/datastructures/mixins.pyi b/src/werkzeug/datastructures/mixins.pyi deleted file mode 100644 index 40453f7..0000000 --- a/src/werkzeug/datastructures/mixins.pyi +++ /dev/null @@ -1,97 +0,0 @@ -from collections.abc import Callable -from collections.abc import Hashable -from collections.abc import Iterable -from typing import Any -from typing import NoReturn -from typing import overload -from typing import SupportsIndex -from typing import TypeVar - -from _typeshed import SupportsKeysAndGetItem - -from .headers import Headers - -K = TypeVar("K") -T = TypeVar("T") -V = TypeVar("V") - -def is_immutable(self: object) -> NoReturn: ... - -class ImmutableListMixin(list[V]): - _hash_cache: int | None - def __hash__(self) -> int: ... # type: ignore - def __delitem__(self, key: SupportsIndex | slice) -> NoReturn: ... - def __iadd__(self, other: Any) -> NoReturn: ... # type: ignore - def __imul__(self, other: SupportsIndex) -> NoReturn: ... - def __setitem__(self, key: int | slice, value: V) -> NoReturn: ... # type: ignore - def append(self, value: V) -> NoReturn: ... - def remove(self, value: V) -> NoReturn: ... - def extend(self, values: Iterable[V]) -> NoReturn: ... - def insert(self, pos: SupportsIndex, value: V) -> NoReturn: ... - def pop(self, index: SupportsIndex = -1) -> NoReturn: ... - def reverse(self) -> NoReturn: ... - def sort( - self, key: Callable[[V], Any] | None = None, reverse: bool = False - ) -> NoReturn: ... - -class ImmutableDictMixin(dict[K, V]): - _hash_cache: int | None - @classmethod - def fromkeys( # type: ignore - cls, keys: Iterable[K], value: V | None = None - ) -> ImmutableDictMixin[K, V]: ... - def _iter_hashitems(self) -> Iterable[Hashable]: ... - def __hash__(self) -> int: ... # type: ignore - def setdefault(self, key: K, default: V | None = None) -> NoReturn: ... - def update(self, *args: Any, **kwargs: V) -> NoReturn: ... - def pop(self, key: K, default: V | None = None) -> NoReturn: ... # type: ignore - def popitem(self) -> NoReturn: ... - def __setitem__(self, key: K, value: V) -> NoReturn: ... - def __delitem__(self, key: K) -> NoReturn: ... - def clear(self) -> NoReturn: ... - -class ImmutableMultiDictMixin(ImmutableDictMixin[K, V]): - def _iter_hashitems(self) -> Iterable[Hashable]: ... - def add(self, key: K, value: V) -> NoReturn: ... - def popitemlist(self) -> NoReturn: ... - def poplist(self, key: K) -> NoReturn: ... - def setlist(self, key: K, new_list: Iterable[V]) -> NoReturn: ... - def setlistdefault( - self, key: K, default_list: Iterable[V] | None = None - ) -> NoReturn: ... - -class ImmutableHeadersMixin(Headers): - def __delitem__(self, key: Any, _index_operation: bool = True) -> NoReturn: ... - def __setitem__(self, key: Any, value: Any) -> NoReturn: ... - def set(self, _key: Any, _value: Any, **kw: Any) -> NoReturn: ... - def setlist(self, key: Any, values: Any) -> NoReturn: ... - def add(self, _key: Any, _value: Any, **kw: Any) -> NoReturn: ... - def add_header(self, _key: Any, _value: Any, **_kw: Any) -> NoReturn: ... - def remove(self, key: Any) -> NoReturn: ... - def extend(self, *args: Any, **kwargs: Any) -> NoReturn: ... - def update(self, *args: Any, **kwargs: Any) -> NoReturn: ... - def insert(self, pos: Any, value: Any) -> NoReturn: ... - def pop(self, key: Any = None, default: Any = ...) -> NoReturn: ... - def popitem(self) -> NoReturn: ... - def setdefault(self, key: Any, default: Any) -> NoReturn: ... - def setlistdefault(self, key: Any, default: Any) -> NoReturn: ... - -def _calls_update(name: str) -> Callable[[UpdateDictMixin[K, V]], Any]: ... - -class UpdateDictMixin(dict[K, V]): - on_update: Callable[[UpdateDictMixin[K, V] | None, None], None] - def setdefault(self, key: K, default: V | None = None) -> V: ... - @overload - def pop(self, key: K) -> V: ... - @overload - def pop(self, key: K, default: V | T = ...) -> V | T: ... - def __setitem__(self, key: K, value: V) -> None: ... - def __delitem__(self, key: K) -> None: ... - def clear(self) -> None: ... - def popitem(self) -> tuple[K, V]: ... - @overload - def update(self, __m: SupportsKeysAndGetItem[K, V], **kwargs: V) -> None: ... - @overload - def update(self, __m: Iterable[tuple[K, V]], **kwargs: V) -> None: ... - @overload - def update(self, **kwargs: V) -> None: ... diff --git a/src/werkzeug/datastructures/range.py b/src/werkzeug/datastructures/range.py index 7011ea4..4c9f67d 100644 --- a/src/werkzeug/datastructures/range.py +++ b/src/werkzeug/datastructures/range.py @@ -1,5 +1,14 @@ from __future__ import annotations +import collections.abc as cabc +import typing as t +from datetime import datetime + +if t.TYPE_CHECKING: + import typing_extensions as te + +T = t.TypeVar("T") + class IfRange: """Very simple object that represents the `If-Range` header in parsed @@ -9,14 +18,14 @@ class IfRange: .. versionadded:: 0.7 """ - def __init__(self, etag=None, date=None): + def __init__(self, etag: str | None = None, date: datetime | None = None): #: The etag parsed and unquoted. Ranges always operate on strong #: etags so the weakness information is not necessary. self.etag = etag #: The date in parsed format or `None`. self.date = date - def to_header(self): + def to_header(self) -> str: """Converts the object back into an HTTP header.""" if self.date is not None: return http.http_date(self.date) @@ -24,10 +33,10 @@ def to_header(self): return http.quote_etag(self.etag) return "" - def __str__(self): + def __str__(self) -> str: return self.to_header() - def __repr__(self): + def __repr__(self) -> str: return f"<{type(self).__name__} {str(self)!r}>" @@ -44,7 +53,9 @@ class Range: .. versionadded:: 0.7 """ - def __init__(self, units, ranges): + def __init__( + self, units: str, ranges: cabc.Sequence[tuple[int, int | None]] + ) -> None: #: The units of this range. Usually "bytes". self.units = units #: A list of ``(begin, end)`` tuples for the range header provided. @@ -55,7 +66,7 @@ def __init__(self, units, ranges): if start is None or (end is not None and (start < 0 or start >= end)): raise ValueError(f"{(start, end)} is not a valid range.") - def range_for_length(self, length): + def range_for_length(self, length: int | None) -> tuple[int, int] | None: """If the range is for bytes, the length is not None and there is exactly one range and it is satisfiable it returns a ``(start, stop)`` tuple, otherwise `None`. @@ -71,7 +82,7 @@ def range_for_length(self, length): return start, min(end, length) return None - def make_content_range(self, length): + def make_content_range(self, length: int | None) -> ContentRange | None: """Creates a :class:`~werkzeug.datastructures.ContentRange` object from the current range and given content length. """ @@ -80,7 +91,7 @@ def make_content_range(self, length): return ContentRange(self.units, rng[0], rng[1], length) return None - def to_header(self): + def to_header(self) -> str: """Converts the object back into an HTTP header.""" ranges = [] for begin, end in self.ranges: @@ -90,7 +101,7 @@ def to_header(self): ranges.append(f"{begin}-{end - 1}") return f"{self.units}={','.join(ranges)}" - def to_content_range_header(self, length): + def to_content_range_header(self, length: int | None) -> str | None: """Converts the object into `Content-Range` HTTP header, based on given length """ @@ -99,23 +110,34 @@ def to_content_range_header(self, length): return f"{self.units} {range[0]}-{range[1] - 1}/{length}" return None - def __str__(self): + def __str__(self) -> str: return self.to_header() - def __repr__(self): + def __repr__(self) -> str: return f"<{type(self).__name__} {str(self)!r}>" -def _callback_property(name): - def fget(self): - return getattr(self, name) +class _CallbackProperty(t.Generic[T]): + def __set_name__(self, owner: type[ContentRange], name: str) -> None: + self.attr = f"_{name}" - def fset(self, value): - setattr(self, name, value) - if self.on_update is not None: - self.on_update(self) + @t.overload + def __get__(self, instance: None, owner: None) -> te.Self: ... + @t.overload + def __get__(self, instance: ContentRange, owner: type[ContentRange]) -> T: ... + def __get__( + self, instance: ContentRange | None, owner: type[ContentRange] | None + ) -> te.Self | T: + if instance is None: + return self - return property(fget, fset) + return instance.__dict__[self.attr] # type: ignore[no-any-return] + + def __set__(self, instance: ContentRange, value: T) -> None: + instance.__dict__[self.attr] = value + + if instance.on_update is not None: + instance.on_update(instance) class ContentRange: @@ -124,55 +146,67 @@ class ContentRange: .. versionadded:: 0.7 """ - def __init__(self, units, start, stop, length=None, on_update=None): - assert http.is_byte_range_valid(start, stop, length), "Bad range provided" + def __init__( + self, + units: str | None, + start: int | None, + stop: int | None, + length: int | None = None, + on_update: cabc.Callable[[ContentRange], None] | None = None, + ) -> None: self.on_update = on_update self.set(start, stop, length, units) #: The units to use, usually "bytes" - units = _callback_property("_units") + units: str | None = _CallbackProperty() # type: ignore[assignment] #: The start point of the range or `None`. - start = _callback_property("_start") + start: int | None = _CallbackProperty() # type: ignore[assignment] #: The stop point of the range (non-inclusive) or `None`. Can only be #: `None` if also start is `None`. - stop = _callback_property("_stop") + stop: int | None = _CallbackProperty() # type: ignore[assignment] #: The length of the range or `None`. - length = _callback_property("_length") - - def set(self, start, stop, length=None, units="bytes"): + length: int | None = _CallbackProperty() # type: ignore[assignment] + + def set( + self, + start: int | None, + stop: int | None, + length: int | None = None, + units: str | None = "bytes", + ) -> None: """Simple method to update the ranges.""" assert http.is_byte_range_valid(start, stop, length), "Bad range provided" - self._units = units - self._start = start - self._stop = stop - self._length = length + self._units: str | None = units + self._start: int | None = start + self._stop: int | None = stop + self._length: int | None = length if self.on_update is not None: self.on_update(self) - def unset(self): + def unset(self) -> None: """Sets the units to `None` which indicates that the header should no longer be used. """ self.set(None, None, units=None) - def to_header(self): - if self.units is None: + def to_header(self) -> str: + if self._units is None: return "" - if self.length is None: - length = "*" + if self._length is None: + length: str | int = "*" else: - length = self.length - if self.start is None: - return f"{self.units} */{length}" - return f"{self.units} {self.start}-{self.stop - 1}/{length}" + length = self._length + if self._start is None: + return f"{self._units} */{length}" + return f"{self._units} {self._start}-{self._stop - 1}/{length}" # type: ignore[operator] - def __bool__(self): - return self.units is not None + def __bool__(self) -> bool: + return self._units is not None - def __str__(self): + def __str__(self) -> str: return self.to_header() - def __repr__(self): + def __repr__(self) -> str: return f"<{type(self).__name__} {str(self)!r}>" diff --git a/src/werkzeug/datastructures/range.pyi b/src/werkzeug/datastructures/range.pyi deleted file mode 100644 index f38ad69..0000000 --- a/src/werkzeug/datastructures/range.pyi +++ /dev/null @@ -1,57 +0,0 @@ -from collections.abc import Callable -from datetime import datetime - -class IfRange: - etag: str | None - date: datetime | None - def __init__( - self, etag: str | None = None, date: datetime | None = None - ) -> None: ... - def to_header(self) -> str: ... - -class Range: - units: str - ranges: list[tuple[int, int | None]] - def __init__(self, units: str, ranges: list[tuple[int, int | None]]) -> None: ... - def range_for_length(self, length: int | None) -> tuple[int, int] | None: ... - def make_content_range(self, length: int | None) -> ContentRange | None: ... - def to_header(self) -> str: ... - def to_content_range_header(self, length: int | None) -> str | None: ... - -def _callback_property(name: str) -> property: ... - -class ContentRange: - on_update: Callable[[ContentRange], None] | None - def __init__( - self, - units: str | None, - start: int | None, - stop: int | None, - length: int | None = None, - on_update: Callable[[ContentRange], None] | None = None, - ) -> None: ... - @property - def units(self) -> str | None: ... - @units.setter - def units(self, value: str | None) -> None: ... - @property - def start(self) -> int | None: ... - @start.setter - def start(self, value: int | None) -> None: ... - @property - def stop(self) -> int | None: ... - @stop.setter - def stop(self, value: int | None) -> None: ... - @property - def length(self) -> int | None: ... - @length.setter - def length(self, value: int | None) -> None: ... - def set( - self, - start: int | None, - stop: int | None, - length: int | None = None, - units: str | None = "bytes", - ) -> None: ... - def unset(self) -> None: ... - def to_header(self) -> str: ... diff --git a/src/werkzeug/datastructures/structures.py b/src/werkzeug/datastructures/structures.py index 4279ceb..dbb7e80 100644 --- a/src/werkzeug/datastructures/structures.py +++ b/src/werkzeug/datastructures/structures.py @@ -1,6 +1,7 @@ from __future__ import annotations -from collections.abc import MutableSet +import collections.abc as cabc +import typing as t from copy import deepcopy from .. import exceptions @@ -10,20 +11,29 @@ from .mixins import ImmutableMultiDictMixin from .mixins import UpdateDictMixin +if t.TYPE_CHECKING: + import typing_extensions as te -def is_immutable(self): - raise TypeError(f"{type(self).__name__!r} objects are immutable") +K = t.TypeVar("K") +V = t.TypeVar("V") +T = t.TypeVar("T") -def iter_multi_items(mapping): +def iter_multi_items( + mapping: ( + MultiDict[K, V] + | cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] + | cabc.Iterable[tuple[K, V]] + ), +) -> cabc.Iterator[tuple[K, V]]: """Iterates over the items of a mapping yielding keys and values without dropping any from more complex structures. """ if isinstance(mapping, MultiDict): yield from mapping.items(multi=True) - elif isinstance(mapping, dict): + elif isinstance(mapping, cabc.Mapping): for key, value in mapping.items(): - if isinstance(value, (tuple, list)): + if isinstance(value, (list, tuple, set)): for v in value: yield key, v else: @@ -32,7 +42,7 @@ def iter_multi_items(mapping): yield from mapping -class ImmutableList(ImmutableListMixin, list): +class ImmutableList(ImmutableListMixin, list[V]): # type: ignore[misc] """An immutable :class:`list`. .. versionadded:: 0.5 @@ -40,11 +50,11 @@ class ImmutableList(ImmutableListMixin, list): :private: """ - def __repr__(self): + def __repr__(self) -> str: return f"{type(self).__name__}({list.__repr__(self)})" -class TypeConversionDict(dict): +class TypeConversionDict(dict[K, V]): """Works like a regular dict but the :meth:`get` method can perform type conversions. :class:`MultiDict` and :class:`CombinedMultiDict` are subclasses of this class and provide the same feature. @@ -52,7 +62,22 @@ class TypeConversionDict(dict): .. versionadded:: 0.5 """ - def get(self, key, default=None, type=None): + @t.overload # type: ignore[override] + def get(self, key: K) -> V | None: ... + @t.overload + def get(self, key: K, default: V) -> V: ... + @t.overload + def get(self, key: K, default: T) -> V | T: ... + @t.overload + def get(self, key: str, type: cabc.Callable[[V], T]) -> T | None: ... + @t.overload + def get(self, key: str, default: T, type: cabc.Callable[[V], T]) -> T: ... + def get( # type: ignore[misc] + self, + key: K, + default: V | T | None = None, + type: cabc.Callable[[V], T] | None = None, + ) -> V | T | None: """Return the default value if the requested data doesn't exist. If `type` is provided and is a callable it should convert the value, return it or raise a :exc:`ValueError` if that is not possible. In @@ -81,33 +106,35 @@ def get(self, key, default=None, type=None): rv = self[key] except KeyError: return default - if type is not None: - try: - rv = type(rv) - except (ValueError, TypeError): - rv = default - return rv + if type is None: + return rv -class ImmutableTypeConversionDict(ImmutableDictMixin, TypeConversionDict): + try: + return type(rv) + except (ValueError, TypeError): + return default + + +class ImmutableTypeConversionDict(ImmutableDictMixin[K, V], TypeConversionDict[K, V]): # type: ignore[misc] """Works like a :class:`TypeConversionDict` but does not support modifications. .. versionadded:: 0.5 """ - def copy(self): + def copy(self) -> TypeConversionDict[K, V]: """Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`). """ return TypeConversionDict(self) - def __copy__(self): + def __copy__(self) -> te.Self: return self -class MultiDict(TypeConversionDict): +class MultiDict(TypeConversionDict[K, V]): """A :class:`MultiDict` is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form @@ -146,42 +173,57 @@ class MultiDict(TypeConversionDict): :param mapping: the initial value for the :class:`MultiDict`. Either a regular dict, an iterable of ``(key, value)`` tuples or `None`. + + .. versionchanged:: 3.1 + Implement ``|`` and ``|=`` operators. """ - def __init__(self, mapping=None): - if isinstance(mapping, MultiDict): - dict.__init__(self, ((k, vs[:]) for k, vs in mapping.lists())) - elif isinstance(mapping, dict): + def __init__( + self, + mapping: ( + MultiDict[K, V] + | cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] + | cabc.Iterable[tuple[K, V]] + | None + ) = None, + ) -> None: + if mapping is None: + super().__init__() + elif isinstance(mapping, MultiDict): + super().__init__((k, vs[:]) for k, vs in mapping.lists()) + elif isinstance(mapping, cabc.Mapping): tmp = {} for key, value in mapping.items(): - if isinstance(value, (tuple, list)): - if len(value) == 0: - continue + if isinstance(value, (list, tuple, set)): value = list(value) + + if not value: + continue else: value = [value] tmp[key] = value - dict.__init__(self, tmp) + super().__init__(tmp) # type: ignore[arg-type] else: tmp = {} - for key, value in mapping or (): + for key, value in mapping: tmp.setdefault(key, []).append(value) - dict.__init__(self, tmp) + super().__init__(tmp) # type: ignore[arg-type] - def __getstate__(self): + def __getstate__(self) -> t.Any: return dict(self.lists()) - def __setstate__(self, value): - dict.clear(self) - dict.update(self, value) + def __setstate__(self, value: t.Any) -> None: + super().clear() + super().update(value) - def __iter__(self): - # Work around https://bugs.python.org/issue43246. - # (`return super().__iter__()` also works here, which makes this look - # even more like it should be a no-op, yet it isn't.) - return dict.__iter__(self) + def __iter__(self) -> cabc.Iterator[K]: + # https://github.com/python/cpython/issues/87412 + # If __iter__ is not overridden, Python uses a fast path for dict(md), + # taking the data directly and getting lists of values, rather than + # calling __getitem__ and getting only the first value. + return super().__iter__() - def __getitem__(self, key): + def __getitem__(self, key: K) -> V: """Return the first data value for this key; raises KeyError if not found. @@ -190,20 +232,20 @@ def __getitem__(self, key): """ if key in self: - lst = dict.__getitem__(self, key) - if len(lst) > 0: - return lst[0] + lst = super().__getitem__(key) + if len(lst) > 0: # type: ignore[arg-type] + return lst[0] # type: ignore[index,no-any-return] raise exceptions.BadRequestKeyError(key) - def __setitem__(self, key, value): + def __setitem__(self, key: K, value: V) -> None: """Like :meth:`add` but removes an existing key first. :param key: the key for the value. :param value: the value to set. """ - dict.__setitem__(self, key, [value]) + super().__setitem__(key, [value]) # type: ignore[assignment] - def add(self, key, value): + def add(self, key: K, value: V) -> None: """Adds a new value for the key. .. versionadded:: 0.6 @@ -211,22 +253,30 @@ def add(self, key, value): :param key: the key for the value. :param value: the value to add. """ - dict.setdefault(self, key, []).append(value) - - def getlist(self, key, type=None): + super().setdefault(key, []).append(value) # type: ignore[arg-type,attr-defined] + + @t.overload + def getlist(self, key: K) -> list[V]: ... + @t.overload + def getlist(self, key: K, type: cabc.Callable[[V], T]) -> list[T]: ... + def getlist( + self, key: K, type: cabc.Callable[[V], T] | None = None + ) -> list[V] | list[T]: """Return the list of items for a given key. If that key is not in the `MultiDict`, the return value will be an empty list. Just like `get`, `getlist` accepts a `type` parameter. All items will be converted with the callable defined there. :param key: The key to be looked up. - :param type: A callable that is used to cast the value in the - :class:`MultiDict`. If a :exc:`ValueError` is raised - by this callable the value will be removed from the list. + :param type: Callable to convert each value. If a ``ValueError`` or + ``TypeError`` is raised, the value is omitted. :return: a :class:`list` of all the values for the key. + + .. versionchanged:: 3.1 + Catches ``TypeError`` in addition to ``ValueError``. """ try: - rv = dict.__getitem__(self, key) + rv: list[V] = super().__getitem__(key) # type: ignore[assignment] except KeyError: return [] if type is None: @@ -235,11 +285,11 @@ def getlist(self, key, type=None): for item in rv: try: result.append(type(item)) - except ValueError: + except (ValueError, TypeError): pass return result - def setlist(self, key, new_list): + def setlist(self, key: K, new_list: cabc.Iterable[V]) -> None: """Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary. @@ -255,9 +305,13 @@ def setlist(self, key, new_list): :param new_list: An iterable with the new values for the key. Old values are removed first. """ - dict.__setitem__(self, key, list(new_list)) + super().__setitem__(key, list(new_list)) # type: ignore[assignment] - def setdefault(self, key, default=None): + @t.overload + def setdefault(self, key: K) -> None: ... + @t.overload + def setdefault(self, key: K, default: V) -> V: ... + def setdefault(self, key: K, default: V | None = None) -> V | None: """Returns the value for the key if it is in the dict, otherwise it returns `default` and sets that value for `key`. @@ -266,12 +320,13 @@ def setdefault(self, key, default=None): in the dict. If not further specified it's `None`. """ if key not in self: - self[key] = default - else: - default = self[key] - return default + self[key] = default # type: ignore[assignment] + + return self[key] - def setlistdefault(self, key, default_list=None): + def setlistdefault( + self, key: K, default_list: cabc.Iterable[V] | None = None + ) -> list[V]: """Like `setdefault` but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items @@ -289,38 +344,42 @@ def setlistdefault(self, key, default_list=None): :return: a :class:`list` """ if key not in self: - default_list = list(default_list or ()) - dict.__setitem__(self, key, default_list) - else: - default_list = dict.__getitem__(self, key) - return default_list + super().__setitem__(key, list(default_list or ())) # type: ignore[assignment] - def items(self, multi=False): + return super().__getitem__(key) # type: ignore[return-value] + + def items(self, multi: bool = False) -> cabc.Iterable[tuple[K, V]]: # type: ignore[override] """Return an iterator of ``(key, value)`` pairs. :param multi: If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key. """ - for key, values in dict.items(self): + values: list[V] + + for key, values in super().items(): # type: ignore[assignment] if multi: for value in values: yield key, value else: yield key, values[0] - def lists(self): + def lists(self) -> cabc.Iterable[tuple[K, list[V]]]: """Return a iterator of ``(key, values)`` pairs, where values is the list of all values associated with the key.""" - for key, values in dict.items(self): + values: list[V] + + for key, values in super().items(): # type: ignore[assignment] yield key, list(values) - def values(self): + def values(self) -> cabc.Iterable[V]: # type: ignore[override] """Returns an iterator of the first value on every key's value list.""" - for values in dict.values(self): + values: list[V] + + for values in super().values(): # type: ignore[assignment] yield values[0] - def listvalues(self): + def listvalues(self) -> cabc.Iterable[list[V]]: """Return an iterator of all values associated with a key. Zipping :meth:`keys` and this is the same as calling :meth:`lists`: @@ -328,17 +387,21 @@ def listvalues(self): >>> zip(d.keys(), d.listvalues()) == d.lists() True """ - return dict.values(self) + return super().values() # type: ignore[return-value] - def copy(self): + def copy(self) -> te.Self: """Return a shallow copy of this object.""" return self.__class__(self) - def deepcopy(self, memo=None): + def deepcopy(self, memo: t.Any = None) -> te.Self: """Return a deep copy of this object.""" return self.__class__(deepcopy(self.to_dict(flat=False), memo)) - def to_dict(self, flat=True): + @t.overload + def to_dict(self) -> dict[K, V]: ... + @t.overload + def to_dict(self, flat: t.Literal[False]) -> dict[K, list[V]]: ... + def to_dict(self, flat: bool = True) -> dict[K, V] | dict[K, list[V]]: """Return the contents as regular dict. If `flat` is `True` the returned dict will only have the first item present, if `flat` is `False` all values will be returned as lists. @@ -352,7 +415,14 @@ def to_dict(self, flat=True): return dict(self.items()) return dict(self.lists()) - def update(self, mapping): + def update( # type: ignore[override] + self, + mapping: ( + MultiDict[K, V] + | cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] + | cabc.Iterable[tuple[K, V]] + ), + ) -> None: """update() extends rather than replaces existing key lists: >>> a = MultiDict({'x': 1}) @@ -371,9 +441,42 @@ def update(self, mapping): MultiDict([]) """ for key, value in iter_multi_items(mapping): - MultiDict.add(self, key, value) + self.add(key, value) - def pop(self, key, default=_missing): + def __or__( # type: ignore[override] + self, other: cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] + ) -> MultiDict[K, V]: + if not isinstance(other, cabc.Mapping): + return NotImplemented + + rv = self.copy() + rv.update(other) + return rv + + def __ior__( # type: ignore[override] + self, + other: ( + cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] + | cabc.Iterable[tuple[K, V]] + ), + ) -> te.Self: + if not isinstance(other, (cabc.Mapping, cabc.Iterable)): + return NotImplemented + + self.update(other) + return self + + @t.overload + def pop(self, key: K) -> V: ... + @t.overload + def pop(self, key: K, default: V) -> V: ... + @t.overload + def pop(self, key: K, default: T) -> V | T: ... + def pop( + self, + key: K, + default: V | T = _missing, # type: ignore[assignment] + ) -> V | T: """Pop the first item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded: @@ -387,8 +490,10 @@ def pop(self, key, default=_missing): :param default: if provided the value to return if the key was not in the dictionary. """ + lst: list[V] + try: - lst = dict.pop(self, key) + lst = super().pop(key) # type: ignore[assignment] if len(lst) == 0: raise exceptions.BadRequestKeyError(key) @@ -400,19 +505,21 @@ def pop(self, key, default=_missing): raise exceptions.BadRequestKeyError(key) from None - def popitem(self): + def popitem(self) -> tuple[K, V]: """Pop an item from the dict.""" + item: tuple[K, list[V]] + try: - item = dict.popitem(self) + item = super().popitem() # type: ignore[assignment] if len(item[1]) == 0: raise exceptions.BadRequestKeyError(item[0]) - return (item[0], item[1][0]) + return item[0], item[1][0] except KeyError as e: raise exceptions.BadRequestKeyError(e.args[0]) from None - def poplist(self, key): + def poplist(self, key: K) -> list[V]: """Pop the list for a key from the dict. If the key is not in the dict an empty list is returned. @@ -420,26 +527,26 @@ def poplist(self, key): If the key does no longer exist a list is returned instead of raising an error. """ - return dict.pop(self, key, []) + return super().pop(key, []) # type: ignore[return-value] - def popitemlist(self): + def popitemlist(self) -> tuple[K, list[V]]: """Pop a ``(key, list)`` tuple from the dict.""" try: - return dict.popitem(self) + return super().popitem() # type: ignore[return-value] except KeyError as e: raise exceptions.BadRequestKeyError(e.args[0]) from None - def __copy__(self): + def __copy__(self) -> te.Self: return self.copy() - def __deepcopy__(self, memo): + def __deepcopy__(self, memo: t.Any) -> te.Self: return self.deepcopy(memo=memo) - def __repr__(self): + def __repr__(self) -> str: return f"{type(self).__name__}({list(self.items(multi=True))!r})" -class _omd_bucket: +class _omd_bucket(t.Generic[K, V]): """Wraps values in the :class:`OrderedMultiDict`. This makes it possible to keep an order over multiple different keys. It requires a lot of extra memory and slows down access a lot, but makes it @@ -448,11 +555,11 @@ class _omd_bucket: __slots__ = ("prev", "key", "value", "next") - def __init__(self, omd, key, value): - self.prev = omd._last_bucket - self.key = key - self.value = value - self.next = None + def __init__(self, omd: _OrderedMultiDict[K, V], key: K, value: V) -> None: + self.prev: _omd_bucket[K, V] | None = omd._last_bucket + self.key: K = key + self.value: V = value + self.next: _omd_bucket[K, V] | None = None if omd._first_bucket is None: omd._first_bucket = self @@ -460,7 +567,7 @@ def __init__(self, omd, key, value): omd._last_bucket.next = self omd._last_bucket = self - def unlink(self, omd): + def unlink(self, omd: _OrderedMultiDict[K, V]) -> None: if self.prev: self.prev.next = self.next if self.next: @@ -471,7 +578,7 @@ def unlink(self, omd): omd._last_bucket = self.prev -class OrderedMultiDict(MultiDict): +class _OrderedMultiDict(MultiDict[K, V]): """Works like a regular :class:`MultiDict` but preserves the order of the fields. To convert the ordered multi dict into a list you can use the :meth:`items` method and pass it ``multi=True``. @@ -485,18 +592,38 @@ class OrderedMultiDict(MultiDict): multi dict into a regular dict by using ``dict(multidict)``. Instead you have to use the :meth:`to_dict` method, otherwise the internal bucket objects are exposed. + + .. deprecated:: 3.1 + Will be removed in Werkzeug 3.2. Use ``MultiDict`` instead. """ - def __init__(self, mapping=None): - dict.__init__(self) - self._first_bucket = self._last_bucket = None + def __init__( + self, + mapping: ( + MultiDict[K, V] + | cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] + | cabc.Iterable[tuple[K, V]] + | None + ) = None, + ) -> None: + import warnings + + warnings.warn( + "'OrderedMultiDict' is deprecated and will be removed in Werkzeug" + " 3.2. Use 'MultiDict' instead.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__() + self._first_bucket: _omd_bucket[K, V] | None = None + self._last_bucket: _omd_bucket[K, V] | None = None if mapping is not None: - OrderedMultiDict.update(self, mapping) + self.update(mapping) - def __eq__(self, other): + def __eq__(self, other: object) -> bool: if not isinstance(other, MultiDict): return NotImplemented - if isinstance(other, OrderedMultiDict): + if isinstance(other, _OrderedMultiDict): iter1 = iter(self.items(multi=True)) iter2 = iter(other.items(multi=True)) try: @@ -518,41 +645,42 @@ def __eq__(self, other): return False return True - __hash__ = None + __hash__ = None # type: ignore[assignment] - def __reduce_ex__(self, protocol): + def __reduce_ex__(self, protocol: t.SupportsIndex) -> t.Any: return type(self), (list(self.items(multi=True)),) - def __getstate__(self): + def __getstate__(self) -> t.Any: return list(self.items(multi=True)) - def __setstate__(self, values): - dict.clear(self) + def __setstate__(self, values: t.Any) -> None: + self.clear() + for key, value in values: self.add(key, value) - def __getitem__(self, key): + def __getitem__(self, key: K) -> V: if key in self: - return dict.__getitem__(self, key)[0].value + return dict.__getitem__(self, key)[0].value # type: ignore[index,no-any-return] raise exceptions.BadRequestKeyError(key) - def __setitem__(self, key, value): + def __setitem__(self, key: K, value: V) -> None: self.poplist(key) self.add(key, value) - def __delitem__(self, key): + def __delitem__(self, key: K) -> None: self.pop(key) - def keys(self): - return (key for key, value in self.items()) + def keys(self) -> cabc.Iterable[K]: # type: ignore[override] + return (key for key, _ in self.items()) - def __iter__(self): + def __iter__(self) -> cabc.Iterator[K]: return iter(self.keys()) - def values(self): + def values(self) -> cabc.Iterable[V]: # type: ignore[override] return (value for key, value in self.items()) - def items(self, multi=False): + def items(self, multi: bool = False) -> cabc.Iterable[tuple[K, V]]: # type: ignore[override] ptr = self._first_bucket if multi: while ptr is not None: @@ -566,7 +694,7 @@ def items(self, multi=False): yield ptr.key, ptr.value ptr = ptr.next - def lists(self): + def lists(self) -> cabc.Iterable[tuple[K, list[V]]]: returned_keys = set() ptr = self._first_bucket while ptr is not None: @@ -575,16 +703,24 @@ def lists(self): returned_keys.add(ptr.key) ptr = ptr.next - def listvalues(self): + def listvalues(self) -> cabc.Iterable[list[V]]: for _key, values in self.lists(): yield values - def add(self, key, value): - dict.setdefault(self, key, []).append(_omd_bucket(self, key, value)) + def add(self, key: K, value: V) -> None: + dict.setdefault(self, key, []).append(_omd_bucket(self, key, value)) # type: ignore[arg-type,attr-defined] + + @t.overload + def getlist(self, key: K) -> list[V]: ... + @t.overload + def getlist(self, key: K, type: cabc.Callable[[V], T]) -> list[T]: ... + def getlist( + self, key: K, type: cabc.Callable[[V], T] | None = None + ) -> list[V] | list[T]: + rv: list[_omd_bucket[K, V]] - def getlist(self, key, type=None): try: - rv = dict.__getitem__(self, key) + rv = dict.__getitem__(self, key) # type: ignore[index] except KeyError: return [] if type is None: @@ -593,31 +729,50 @@ def getlist(self, key, type=None): for item in rv: try: result.append(type(item.value)) - except ValueError: + except (ValueError, TypeError): pass return result - def setlist(self, key, new_list): + def setlist(self, key: K, new_list: cabc.Iterable[V]) -> None: self.poplist(key) for value in new_list: self.add(key, value) - def setlistdefault(self, key, default_list=None): + def setlistdefault(self, key: t.Any, default_list: t.Any = None) -> t.NoReturn: raise TypeError("setlistdefault is unsupported for ordered multi dicts") - def update(self, mapping): + def update( # type: ignore[override] + self, + mapping: ( + MultiDict[K, V] + | cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] + | cabc.Iterable[tuple[K, V]] + ), + ) -> None: for key, value in iter_multi_items(mapping): - OrderedMultiDict.add(self, key, value) + self.add(key, value) - def poplist(self, key): - buckets = dict.pop(self, key, ()) + def poplist(self, key: K) -> list[V]: + buckets: cabc.Iterable[_omd_bucket[K, V]] = dict.pop(self, key, ()) # type: ignore[arg-type] for bucket in buckets: bucket.unlink(self) return [x.value for x in buckets] - def pop(self, key, default=_missing): + @t.overload + def pop(self, key: K) -> V: ... + @t.overload + def pop(self, key: K, default: V) -> V: ... + @t.overload + def pop(self, key: K, default: T) -> V | T: ... + def pop( + self, + key: K, + default: V | T = _missing, # type: ignore[assignment] + ) -> V | T: + buckets: list[_omd_bucket[K, V]] + try: - buckets = dict.pop(self, key) + buckets = dict.pop(self, key) # type: ignore[arg-type] except KeyError: if default is not _missing: return default @@ -629,9 +784,12 @@ def pop(self, key, default=_missing): return buckets[0].value - def popitem(self): + def popitem(self) -> tuple[K, V]: + key: K + buckets: list[_omd_bucket[K, V]] + try: - key, buckets = dict.popitem(self) + key, buckets = dict.popitem(self) # type: ignore[arg-type,assignment] except KeyError as e: raise exceptions.BadRequestKeyError(e.args[0]) from None @@ -640,9 +798,12 @@ def popitem(self): return key, buckets[0].value - def popitemlist(self): + def popitemlist(self) -> tuple[K, list[V]]: + key: K + buckets: list[_omd_bucket[K, V]] + try: - key, buckets = dict.popitem(self) + key, buckets = dict.popitem(self) # type: ignore[arg-type,assignment] except KeyError as e: raise exceptions.BadRequestKeyError(e.args[0]) from None @@ -652,7 +813,7 @@ def popitemlist(self): return key, [x.value for x in buckets] -class CombinedMultiDict(ImmutableMultiDictMixin, MultiDict): +class CombinedMultiDict(ImmutableMultiDictMixin[K, V], MultiDict[K, V]): # type: ignore[misc] """A read only :class:`MultiDict` that you can pass multiple :class:`MultiDict` instances as sequence and it will combine the return values of all wrapped dicts: @@ -675,54 +836,80 @@ class CombinedMultiDict(ImmutableMultiDictMixin, MultiDict): exceptions. """ - def __reduce_ex__(self, protocol): + def __reduce_ex__(self, protocol: t.SupportsIndex) -> t.Any: return type(self), (self.dicts,) - def __init__(self, dicts=None): - self.dicts = list(dicts) or [] + def __init__(self, dicts: cabc.Iterable[MultiDict[K, V]] | None = None) -> None: + super().__init__() + self.dicts: list[MultiDict[K, V]] = list(dicts or ()) @classmethod - def fromkeys(cls, keys, value=None): + def fromkeys(cls, keys: t.Any, value: t.Any = None) -> t.NoReturn: raise TypeError(f"cannot create {cls.__name__!r} instances by fromkeys") - def __getitem__(self, key): + def __getitem__(self, key: K) -> V: for d in self.dicts: if key in d: return d[key] raise exceptions.BadRequestKeyError(key) - def get(self, key, default=None, type=None): + @t.overload # type: ignore[override] + def get(self, key: K) -> V | None: ... + @t.overload + def get(self, key: K, default: V) -> V: ... + @t.overload + def get(self, key: K, default: T) -> V | T: ... + @t.overload + def get(self, key: str, type: cabc.Callable[[V], T]) -> T | None: ... + @t.overload + def get(self, key: str, default: T, type: cabc.Callable[[V], T]) -> T: ... + def get( # type: ignore[misc] + self, + key: K, + default: V | T | None = None, + type: cabc.Callable[[V], T] | None = None, + ) -> V | T | None: for d in self.dicts: if key in d: if type is not None: try: return type(d[key]) - except ValueError: + except (ValueError, TypeError): continue return d[key] return default - def getlist(self, key, type=None): + @t.overload + def getlist(self, key: K) -> list[V]: ... + @t.overload + def getlist(self, key: K, type: cabc.Callable[[V], T]) -> list[T]: ... + def getlist( + self, key: K, type: cabc.Callable[[V], T] | None = None + ) -> list[V] | list[T]: rv = [] for d in self.dicts: - rv.extend(d.getlist(key, type)) + rv.extend(d.getlist(key, type)) # type: ignore[arg-type] return rv - def _keys_impl(self): + def _keys_impl(self) -> set[K]: """This function exists so __len__ can be implemented more efficiently, saving one list creation from an iterator. """ - rv = set() - rv.update(*self.dicts) - return rv + return set(k for d in self.dicts for k in d) - def keys(self): + def keys(self) -> cabc.Iterable[K]: # type: ignore[override] return self._keys_impl() - def __iter__(self): - return iter(self.keys()) + def __iter__(self) -> cabc.Iterator[K]: + return iter(self._keys_impl()) - def items(self, multi=False): + @t.overload # type: ignore[override] + def items(self) -> cabc.Iterable[tuple[K, V]]: ... + @t.overload + def items(self, multi: t.Literal[True]) -> cabc.Iterable[tuple[K, list[V]]]: ... + def items( + self, multi: bool = False + ) -> cabc.Iterable[tuple[K, V]] | cabc.Iterable[tuple[K, list[V]]]: found = set() for d in self.dicts: for key, value in d.items(multi): @@ -732,21 +919,21 @@ def items(self, multi=False): found.add(key) yield key, value - def values(self): - for _key, value in self.items(): + def values(self) -> cabc.Iterable[V]: # type: ignore[override] + for _, value in self.items(): yield value - def lists(self): - rv = {} + def lists(self) -> cabc.Iterable[tuple[K, list[V]]]: + rv: dict[K, list[V]] = {} for d in self.dicts: for key, values in d.lists(): rv.setdefault(key, []).extend(values) - return list(rv.items()) + return rv.items() - def listvalues(self): + def listvalues(self) -> cabc.Iterable[list[V]]: return (x[1] for x in self.lists()) - def copy(self): + def copy(self) -> MultiDict[K, V]: # type: ignore[override] """Return a shallow mutable copy of this object. This returns a :class:`MultiDict` representing the data at the @@ -758,105 +945,118 @@ def copy(self): """ return MultiDict(self) - def to_dict(self, flat=True): - """Return the contents as regular dict. If `flat` is `True` the - returned dict will only have the first item present, if `flat` is - `False` all values will be returned as lists. - - :param flat: If set to `False` the dict returned will have lists - with all the values in it. Otherwise it will only - contain the first item for each key. - :return: a :class:`dict` - """ - if flat: - return dict(self.items()) - - return dict(self.lists()) - - def __len__(self): + def __len__(self) -> int: return len(self._keys_impl()) - def __contains__(self, key): + def __contains__(self, key: K) -> bool: # type: ignore[override] for d in self.dicts: if key in d: return True return False - def __repr__(self): + def __repr__(self) -> str: return f"{type(self).__name__}({self.dicts!r})" -class ImmutableDict(ImmutableDictMixin, dict): +class ImmutableDict(ImmutableDictMixin[K, V], dict[K, V]): # type: ignore[misc] """An immutable :class:`dict`. .. versionadded:: 0.5 """ - def __repr__(self): + def __repr__(self) -> str: return f"{type(self).__name__}({dict.__repr__(self)})" - def copy(self): + def copy(self) -> dict[K, V]: """Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`). """ return dict(self) - def __copy__(self): + def __copy__(self) -> te.Self: return self -class ImmutableMultiDict(ImmutableMultiDictMixin, MultiDict): +class ImmutableMultiDict(ImmutableMultiDictMixin[K, V], MultiDict[K, V]): # type: ignore[misc] """An immutable :class:`MultiDict`. .. versionadded:: 0.5 """ - def copy(self): + def copy(self) -> MultiDict[K, V]: # type: ignore[override] """Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`). """ return MultiDict(self) - def __copy__(self): + def __copy__(self) -> te.Self: return self -class ImmutableOrderedMultiDict(ImmutableMultiDictMixin, OrderedMultiDict): +class _ImmutableOrderedMultiDict( # type: ignore[misc] + ImmutableMultiDictMixin[K, V], _OrderedMultiDict[K, V] +): """An immutable :class:`OrderedMultiDict`. + .. deprecated:: 3.1 + Will be removed in Werkzeug 3.2. Use ``ImmutableMultiDict`` instead. + .. versionadded:: 0.6 """ - def _iter_hashitems(self): + def __init__( + self, + mapping: ( + MultiDict[K, V] + | cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] + | cabc.Iterable[tuple[K, V]] + | None + ) = None, + ) -> None: + super().__init__() + + if mapping is not None: + for k, v in iter_multi_items(mapping): + _OrderedMultiDict.add(self, k, v) + + def _iter_hashitems(self) -> cabc.Iterable[t.Any]: return enumerate(self.items(multi=True)) - def copy(self): + def copy(self) -> _OrderedMultiDict[K, V]: # type: ignore[override] """Return a shallow mutable copy of this object. Keep in mind that the standard library's :func:`copy` function is a no-op for this class like for any other python immutable type (eg: :class:`tuple`). """ - return OrderedMultiDict(self) + return _OrderedMultiDict(self) - def __copy__(self): + def __copy__(self) -> te.Self: return self -class CallbackDict(UpdateDictMixin, dict): +class CallbackDict(UpdateDictMixin[K, V], dict[K, V]): """A dict that calls a function passed every time something is changed. The function is passed the dict instance. """ - def __init__(self, initial=None, on_update=None): - dict.__init__(self, initial or ()) + def __init__( + self, + initial: cabc.Mapping[K, V] | cabc.Iterable[tuple[K, V]] | None = None, + on_update: cabc.Callable[[te.Self], None] | None = None, + ) -> None: + if initial is None: + super().__init__() + else: + super().__init__(initial) + self.on_update = on_update - def __repr__(self): - return f"<{type(self).__name__} {dict.__repr__(self)}>" + def __repr__(self) -> str: + return f"<{type(self).__name__} {super().__repr__()}>" -class HeaderSet(MutableSet): +class HeaderSet(cabc.MutableSet[str]): """Similar to the :class:`ETags` class this implements a set-like structure. Unlike :class:`ETags` this is case insensitive and used for vary, allow, and content-language headers. @@ -869,16 +1069,20 @@ class HeaderSet(MutableSet): HeaderSet(['foo', 'bar', 'baz']) """ - def __init__(self, headers=None, on_update=None): + def __init__( + self, + headers: cabc.Iterable[str] | None = None, + on_update: cabc.Callable[[te.Self], None] | None = None, + ) -> None: self._headers = list(headers or ()) self._set = {x.lower() for x in self._headers} self.on_update = on_update - def add(self, header): + def add(self, header: str) -> None: """Add a new header to the set.""" self.update((header,)) - def remove(self, header): + def remove(self: te.Self, header: str) -> None: """Remove a header from the set. This raises an :exc:`KeyError` if the header is not in the set. @@ -899,7 +1103,7 @@ def remove(self, header): if self.on_update is not None: self.on_update(self) - def update(self, iterable): + def update(self: te.Self, iterable: cabc.Iterable[str]) -> None: """Add all the headers from the iterable to the set. :param iterable: updates the set with the items from the iterable. @@ -914,7 +1118,7 @@ def update(self, iterable): if inserted_any and self.on_update is not None: self.on_update(self) - def discard(self, header): + def discard(self, header: str) -> None: """Like :meth:`remove` but ignores errors. :param header: the header to be discarded. @@ -924,7 +1128,7 @@ def discard(self, header): except KeyError: pass - def find(self, header): + def find(self, header: str) -> int: """Return the index of the header in the set or return -1 if not found. :param header: the header to be looked up. @@ -935,7 +1139,7 @@ def find(self, header): return idx return -1 - def index(self, header): + def index(self, header: str) -> int: """Return the index of the header in the set or raise an :exc:`IndexError`. @@ -946,14 +1150,15 @@ def index(self, header): raise IndexError(header) return rv - def clear(self): + def clear(self: te.Self) -> None: """Clear the set.""" self._set.clear() - del self._headers[:] + self._headers.clear() + if self.on_update is not None: self.on_update(self) - def as_set(self, preserve_casing=False): + def as_set(self, preserve_casing: bool = False) -> set[str]: """Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. @@ -966,20 +1171,20 @@ def as_set(self, preserve_casing=False): return set(self._headers) return set(self._set) - def to_header(self): + def to_header(self) -> str: """Convert the header set into an HTTP header string.""" return ", ".join(map(http.quote_header_value, self._headers)) - def __getitem__(self, idx): + def __getitem__(self, idx: t.SupportsIndex) -> str: return self._headers[idx] - def __delitem__(self, idx): + def __delitem__(self: te.Self, idx: t.SupportsIndex) -> None: rv = self._headers.pop(idx) self._set.remove(rv.lower()) if self.on_update is not None: self.on_update(self) - def __setitem__(self, idx, value): + def __setitem__(self: te.Self, idx: t.SupportsIndex, value: str) -> None: old = self._headers[idx] self._set.remove(old.lower()) self._headers[idx] = value @@ -987,24 +1192,48 @@ def __setitem__(self, idx, value): if self.on_update is not None: self.on_update(self) - def __contains__(self, header): + def __contains__(self, header: str) -> bool: # type: ignore[override] return header.lower() in self._set - def __len__(self): + def __len__(self) -> int: return len(self._set) - def __iter__(self): + def __iter__(self) -> cabc.Iterator[str]: return iter(self._headers) - def __bool__(self): + def __bool__(self) -> bool: return bool(self._set) - def __str__(self): + def __str__(self) -> str: return self.to_header() - def __repr__(self): + def __repr__(self) -> str: return f"{type(self).__name__}({self._headers!r})" # circular dependencies from .. import http + + +def __getattr__(name: str) -> t.Any: + import warnings + + if name == "OrderedMultiDict": + warnings.warn( + "'OrderedMultiDict' is deprecated and will be removed in Werkzeug" + " 3.2. Use 'MultiDict' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _OrderedMultiDict + + if name == "ImmutableOrderedMultiDict": + warnings.warn( + "'ImmutableOrderedMultiDict' is deprecated and will be removed in" + " Werkzeug 3.2. Use 'ImmutableMultiDict' instead.", + DeprecationWarning, + stacklevel=2, + ) + return _ImmutableOrderedMultiDict + + raise AttributeError(name) diff --git a/src/werkzeug/datastructures/structures.pyi b/src/werkzeug/datastructures/structures.pyi deleted file mode 100644 index 7086dda..0000000 --- a/src/werkzeug/datastructures/structures.pyi +++ /dev/null @@ -1,206 +0,0 @@ -from collections.abc import Callable -from collections.abc import Iterable -from collections.abc import Iterator -from collections.abc import Mapping -from typing import Any -from typing import Generic -from typing import Literal -from typing import NoReturn -from typing import overload -from typing import TypeVar - -from .mixins import ImmutableDictMixin -from .mixins import ImmutableListMixin -from .mixins import ImmutableMultiDictMixin -from .mixins import UpdateDictMixin - -D = TypeVar("D") -K = TypeVar("K") -T = TypeVar("T") -V = TypeVar("V") -_CD = TypeVar("_CD", bound="CallbackDict[Any, Any]") - -def is_immutable(self: object) -> NoReturn: ... -def iter_multi_items( - mapping: Mapping[K, V | Iterable[V]] | Iterable[tuple[K, V]], -) -> Iterator[tuple[K, V]]: ... - -class ImmutableList(ImmutableListMixin[V]): ... - -class TypeConversionDict(dict[K, V]): - @overload - def get(self, key: K, default: None = ..., type: None = ...) -> V | None: ... - @overload - def get(self, key: K, default: D, type: None = ...) -> D | V: ... - @overload - def get(self, key: K, default: D, type: Callable[[V], T]) -> D | T: ... - @overload - def get(self, key: K, type: Callable[[V], T]) -> T | None: ... - -class ImmutableTypeConversionDict(ImmutableDictMixin[K, V], TypeConversionDict[K, V]): - def copy(self) -> TypeConversionDict[K, V]: ... - def __copy__(self) -> ImmutableTypeConversionDict[K, V]: ... - -class MultiDict(TypeConversionDict[K, V]): - def __init__( - self, - mapping: Mapping[K, Iterable[V] | V] | Iterable[tuple[K, V]] | None = None, - ) -> None: ... - def __getitem__(self, item: K) -> V: ... - def __setitem__(self, key: K, value: V) -> None: ... - def add(self, key: K, value: V) -> None: ... - @overload - def getlist(self, key: K) -> list[V]: ... - @overload - def getlist(self, key: K, type: Callable[[V], T] = ...) -> list[T]: ... - def setlist(self, key: K, new_list: Iterable[V]) -> None: ... - def setdefault(self, key: K, default: V | None = None) -> V: ... - def setlistdefault( - self, key: K, default_list: Iterable[V] | None = None - ) -> list[V]: ... - def items(self, multi: bool = False) -> Iterator[tuple[K, V]]: ... # type: ignore - def lists(self) -> Iterator[tuple[K, list[V]]]: ... - def values(self) -> Iterator[V]: ... # type: ignore - def listvalues(self) -> Iterator[list[V]]: ... - def copy(self) -> MultiDict[K, V]: ... - def deepcopy(self, memo: Any = None) -> MultiDict[K, V]: ... - @overload - def to_dict(self) -> dict[K, V]: ... - @overload - def to_dict(self, flat: Literal[False]) -> dict[K, list[V]]: ... - def update( # type: ignore - self, mapping: Mapping[K, Iterable[V] | V] | Iterable[tuple[K, V]] - ) -> None: ... - @overload - def pop(self, key: K) -> V: ... - @overload - def pop(self, key: K, default: V | T = ...) -> V | T: ... - def popitem(self) -> tuple[K, V]: ... - def poplist(self, key: K) -> list[V]: ... - def popitemlist(self) -> tuple[K, list[V]]: ... - def __copy__(self) -> MultiDict[K, V]: ... - def __deepcopy__(self, memo: Any) -> MultiDict[K, V]: ... - -class _omd_bucket(Generic[K, V]): - prev: _omd_bucket[K, V] | None - next: _omd_bucket[K, V] | None - key: K - value: V - def __init__(self, omd: OrderedMultiDict[K, V], key: K, value: V) -> None: ... - def unlink(self, omd: OrderedMultiDict[K, V]) -> None: ... - -class OrderedMultiDict(MultiDict[K, V]): - _first_bucket: _omd_bucket[K, V] | None - _last_bucket: _omd_bucket[K, V] | None - def __init__(self, mapping: Mapping[K, V] | None = None) -> None: ... - def __eq__(self, other: object) -> bool: ... - def __getitem__(self, key: K) -> V: ... - def __setitem__(self, key: K, value: V) -> None: ... - def __delitem__(self, key: K) -> None: ... - def keys(self) -> Iterator[K]: ... # type: ignore - def __iter__(self) -> Iterator[K]: ... - def values(self) -> Iterator[V]: ... # type: ignore - def items(self, multi: bool = False) -> Iterator[tuple[K, V]]: ... # type: ignore - def lists(self) -> Iterator[tuple[K, list[V]]]: ... - def listvalues(self) -> Iterator[list[V]]: ... - def add(self, key: K, value: V) -> None: ... - @overload - def getlist(self, key: K) -> list[V]: ... - @overload - def getlist(self, key: K, type: Callable[[V], T] = ...) -> list[T]: ... - def setlist(self, key: K, new_list: Iterable[V]) -> None: ... - def setlistdefault( - self, key: K, default_list: Iterable[V] | None = None - ) -> list[V]: ... - def update( # type: ignore - self, mapping: Mapping[K, V] | Iterable[tuple[K, V]] - ) -> None: ... - def poplist(self, key: K) -> list[V]: ... - @overload - def pop(self, key: K) -> V: ... - @overload - def pop(self, key: K, default: V | T = ...) -> V | T: ... - def popitem(self) -> tuple[K, V]: ... - def popitemlist(self) -> tuple[K, list[V]]: ... - -class CombinedMultiDict(ImmutableMultiDictMixin[K, V], MultiDict[K, V]): # type: ignore - dicts: list[MultiDict[K, V]] - def __init__(self, dicts: Iterable[MultiDict[K, V]] | None) -> None: ... - @classmethod - def fromkeys(cls, keys: Any, value: Any = None) -> NoReturn: ... - def __getitem__(self, key: K) -> V: ... - @overload # type: ignore - def get(self, key: K) -> V | None: ... - @overload - def get(self, key: K, default: V | T = ...) -> V | T: ... - @overload - def get( - self, key: K, default: T | None = None, type: Callable[[V], T] = ... - ) -> T | None: ... - @overload - def getlist(self, key: K) -> list[V]: ... - @overload - def getlist(self, key: K, type: Callable[[V], T] = ...) -> list[T]: ... - def _keys_impl(self) -> set[K]: ... - def keys(self) -> set[K]: ... # type: ignore - def __iter__(self) -> set[K]: ... # type: ignore - def items(self, multi: bool = False) -> Iterator[tuple[K, V]]: ... # type: ignore - def values(self) -> Iterator[V]: ... # type: ignore - def lists(self) -> Iterator[tuple[K, list[V]]]: ... - def listvalues(self) -> Iterator[list[V]]: ... - def copy(self) -> MultiDict[K, V]: ... - @overload - def to_dict(self) -> dict[K, V]: ... - @overload - def to_dict(self, flat: Literal[False]) -> dict[K, list[V]]: ... - def __contains__(self, key: K) -> bool: ... # type: ignore - def has_key(self, key: K) -> bool: ... - -class ImmutableDict(ImmutableDictMixin[K, V], dict[K, V]): - def copy(self) -> dict[K, V]: ... - def __copy__(self) -> ImmutableDict[K, V]: ... - -class ImmutableMultiDict( # type: ignore - ImmutableMultiDictMixin[K, V], MultiDict[K, V] -): - def copy(self) -> MultiDict[K, V]: ... - def __copy__(self) -> ImmutableMultiDict[K, V]: ... - -class ImmutableOrderedMultiDict( # type: ignore - ImmutableMultiDictMixin[K, V], OrderedMultiDict[K, V] -): - def _iter_hashitems(self) -> Iterator[tuple[int, tuple[K, V]]]: ... - def copy(self) -> OrderedMultiDict[K, V]: ... - def __copy__(self) -> ImmutableOrderedMultiDict[K, V]: ... - -class CallbackDict(UpdateDictMixin[K, V], dict[K, V]): - def __init__( - self, - initial: Mapping[K, V] | Iterable[tuple[K, V]] | None = None, - on_update: Callable[[_CD], None] | None = None, - ) -> None: ... - -class HeaderSet(set[str]): - _headers: list[str] - _set: set[str] - on_update: Callable[[HeaderSet], None] | None - def __init__( - self, - headers: Iterable[str] | None = None, - on_update: Callable[[HeaderSet], None] | None = None, - ) -> None: ... - def add(self, header: str) -> None: ... - def remove(self, header: str) -> None: ... - def update(self, iterable: Iterable[str]) -> None: ... # type: ignore - def discard(self, header: str) -> None: ... - def find(self, header: str) -> int: ... - def index(self, header: str) -> int: ... - def clear(self) -> None: ... - def as_set(self, preserve_casing: bool = False) -> set[str]: ... - def to_header(self) -> str: ... - def __getitem__(self, idx: int) -> str: ... - def __delitem__(self, idx: int) -> None: ... - def __setitem__(self, idx: int, value: str) -> None: ... - def __contains__(self, header: str) -> bool: ... # type: ignore - def __len__(self) -> int: ... - def __iter__(self) -> Iterator[str]: ... diff --git a/src/werkzeug/debug/__init__.py b/src/werkzeug/debug/__init__.py index 6bef30f..0c4cabd 100644 --- a/src/werkzeug/debug/__init__.py +++ b/src/werkzeug/debug/__init__.py @@ -13,6 +13,7 @@ from contextlib import ExitStack from io import BytesIO from itertools import chain +from multiprocessing import Value from os.path import basename from os.path import join from zlib import adler32 @@ -172,7 +173,8 @@ def get_pin_and_cookie_name( # App Engine. It may also raise a KeyError if the UID does not # have a username, such as in Docker. username = getpass.getuser() - except (ImportError, KeyError): + # Python >= 3.13 only raises OSError + except (ImportError, KeyError, OSError): username = None mod = sys.modules.get(modname) @@ -286,7 +288,7 @@ def __init__( self.console_init_func = console_init_func self.show_hidden_frames = show_hidden_frames self.secret = gen_salt(20) - self._failed_pin_auth = 0 + self._failed_pin_auth = Value("B") self.pin_logging = pin_logging if pin_security: @@ -375,7 +377,7 @@ def debug_application( environ["wsgi.errors"].write("".join(tb.render_traceback_text())) - def execute_command( # type: ignore[return] + def execute_command( self, request: Request, command: str, @@ -454,8 +456,11 @@ def check_host_trust(self, environ: WSGIEnvironment) -> bool: return host_is_trusted(environ.get("HTTP_HOST"), self.trusted_hosts) def _fail_pin_auth(self) -> None: - time.sleep(5.0 if self._failed_pin_auth > 5 else 0.5) - self._failed_pin_auth += 1 + with self._failed_pin_auth.get_lock(): + count = self._failed_pin_auth.value + self._failed_pin_auth.value = count + 1 + + time.sleep(5.0 if count > 5 else 0.5) def pin_auth(self, request: Request) -> Response: """Authenticates with the pin.""" @@ -482,7 +487,7 @@ def pin_auth(self, request: Request) -> Response: auth = True # If we failed too many times, then we're locked out. - elif self._failed_pin_auth > 10: + elif self._failed_pin_auth.value > 10: exhausted = True # Otherwise go through pin based authentication @@ -490,7 +495,7 @@ def pin_auth(self, request: Request) -> Response: entered_pin = request.args["pin"] if entered_pin.strip().replace("-", "") == pin.replace("-", ""): - self._failed_pin_auth = 0 + self._failed_pin_auth.value = 0 auth = True else: self._fail_pin_auth() diff --git a/src/werkzeug/debug/shared/debugger.js b/src/werkzeug/debug/shared/debugger.js index 18c6583..809b14a 100644 --- a/src/werkzeug/debug/shared/debugger.js +++ b/src/werkzeug/debug/shared/debugger.js @@ -37,18 +37,22 @@ function wrapPlainTraceback() { plainTraceback.replaceWith(wrapper); } +function makeDebugURL(args) { + const params = new URLSearchParams(args) + params.set("s", SECRET) + return `?__debugger__=yes&${params}` +} + function initPinBox() { document.querySelector(".pin-prompt form").addEventListener( "submit", function (event) { event.preventDefault(); - const pin = encodeURIComponent(this.pin.value); - const encodedSecret = encodeURIComponent(SECRET); const btn = this.btn; btn.disabled = true; fetch( - `${document.location}?__debugger__=yes&cmd=pinauth&pin=${pin}&s=${encodedSecret}` + makeDebugURL({cmd: "pinauth", pin: this.pin.value}) ) .then((res) => res.json()) .then(({auth, exhausted}) => { @@ -77,10 +81,7 @@ function initPinBox() { function promptForPin() { if (!EVALEX_TRUSTED) { - const encodedSecret = encodeURIComponent(SECRET); - fetch( - `${document.location}?__debugger__=yes&cmd=printpin&s=${encodedSecret}` - ); + fetch(makeDebugURL({cmd: "printpin"})); const pinPrompt = document.getElementsByClassName("pin-prompt")[0]; fadeIn(pinPrompt); document.querySelector('.pin-prompt input[name="pin"]').focus(); @@ -237,7 +238,7 @@ function createConsoleInput() { function createIconForConsole() { const img = document.createElement("img"); - img.setAttribute("src", "?__debugger__=yes&cmd=resource&f=console.png"); + img.setAttribute("src", makeDebugURL({cmd: "resource", f: "console.png"})); img.setAttribute("title", "Open an interactive python shell in this frame"); return img; } @@ -263,24 +264,7 @@ function handleConsoleSubmit(e, command, frameID) { e.preventDefault(); return new Promise((resolve) => { - // Get input command. - const cmd = command.value; - - // Setup GET request. - const urlPath = ""; - const params = { - __debugger__: "yes", - cmd: cmd, - frm: frameID, - s: SECRET, - }; - const paramString = Object.keys(params) - .map((key) => { - return "&" + encodeURIComponent(key) + "=" + encodeURIComponent(params[key]); - }) - .join(""); - - fetch(urlPath + "?" + paramString) + fetch(makeDebugURL({cmd: command.value, frm: frameID})) .then((res) => { return res.text(); }) diff --git a/src/werkzeug/debug/tbtools.py b/src/werkzeug/debug/tbtools.py index 0574c96..d922893 100644 --- a/src/werkzeug/debug/tbtools.py +++ b/src/werkzeug/debug/tbtools.py @@ -185,7 +185,7 @@ def _process_traceback( "globals": f.f_globals, } - if hasattr(fs, "colno"): + if sys.version_info >= (3, 11): frame_args["colno"] = fs.colno frame_args["end_colno"] = fs.end_colno @@ -296,7 +296,12 @@ def render_traceback_html(self, include_title: bool = True) -> str: rows.append("\n".join(row_parts)) - is_syntax_error = issubclass(self._te.exc_type, SyntaxError) + if sys.version_info < (3, 13): + exc_type_str = self._te.exc_type.__name__ + else: + exc_type_str = self._te.exc_type_str + + is_syntax_error = exc_type_str == "SyntaxError" if include_title: if is_syntax_error: @@ -325,13 +330,19 @@ def render_debugger_html( ) -> str: exc_lines = list(self._te.format_exception_only()) plaintext = "".join(self._te.format()) + + if sys.version_info < (3, 13): + exc_type_str = self._te.exc_type.__name__ + else: + exc_type_str = self._te.exc_type_str + return PAGE_HTML % { "evalex": "true" if evalex else "false", "evalex_trusted": "true" if evalex_trusted else "false", "console": "false", "title": escape(exc_lines[0]), "exception": escape("".join(exc_lines)), - "exception_type": escape(self._te.exc_type.__name__), + "exception_type": escape(exc_type_str), "summary": self.render_traceback_html(include_title=False), "plaintext": escape(plaintext), "plaintext_cs": re.sub("-{2,}", "-", plaintext), diff --git a/src/werkzeug/exceptions.py b/src/werkzeug/exceptions.py index 6ce7ef9..1cd9997 100644 --- a/src/werkzeug/exceptions.py +++ b/src/werkzeug/exceptions.py @@ -197,7 +197,7 @@ class BadRequestKeyError(BadRequest, KeyError): #: useful in a debug mode. show_exception = False - def __init__(self, arg: str | None = None, *args: t.Any, **kwargs: t.Any): + def __init__(self, arg: object | None = None, *args: t.Any, **kwargs: t.Any): super().__init__(*args, **kwargs) if arg is None: @@ -571,6 +571,19 @@ class ImATeapot(HTTPException): description = "This server is a teapot, not a coffee machine" +class MisdirectedRequest(HTTPException): + """421 Misdirected Request + + Indicates that the request was directed to a server that is not able to + produce a response. + + .. versionadded:: 3.1 + """ + + code = 421 + description = "The server is not able to produce a response." + + class UnprocessableEntity(HTTPException): """*422* `Unprocessable Entity` diff --git a/src/werkzeug/formparser.py b/src/werkzeug/formparser.py index ba84721..0103414 100644 --- a/src/werkzeug/formparser.py +++ b/src/werkzeug/formparser.py @@ -33,7 +33,7 @@ from _typeshed.wsgi import WSGIEnvironment - t_parse_result = t.Tuple[ + t_parse_result = tuple[ t.IO[bytes], MultiDict[str, str], MultiDict[str, FileStorage] ] @@ -281,15 +281,11 @@ def _parse_urlencoded( ): raise RequestEntityTooLarge() - try: - items = parse_qsl( - stream.read().decode(), - keep_blank_values=True, - errors="werkzeug.url_quote", - ) - except ValueError as e: - raise RequestEntityTooLarge() from e - + items = parse_qsl( + stream.read().decode(), + keep_blank_values=True, + errors="werkzeug.url_quote", + ) return stream, self.cls(items), self.cls() @@ -356,6 +352,7 @@ def parse( self, stream: t.IO[bytes], boundary: bytes, content_length: int | None ) -> tuple[MultiDict[str, str], MultiDict[str, FileStorage]]: current_part: Field | File + field_size: int | None = None container: t.IO[bytes] | list[bytes] _write: t.Callable[[bytes], t.Any] @@ -374,13 +371,23 @@ def parse( while not isinstance(event, (Epilogue, NeedData)): if isinstance(event, Field): current_part = event + field_size = 0 container = [] _write = container.append elif isinstance(event, File): current_part = event + field_size = None container = self.start_file_streaming(event, content_length) _write = container.write elif isinstance(event, Data): + if self.max_form_memory_size is not None and field_size is not None: + # Ensure that accumulated data events do not exceed limit. + # Also checked within single event in MultipartDecoder. + field_size += len(event.data) + + if field_size > self.max_form_memory_size: + raise RequestEntityTooLarge() + _write(event.data) if not event.more_data: if isinstance(current_part, Field): diff --git a/src/werkzeug/http.py b/src/werkzeug/http.py index 27fa9af..f1dbb85 100644 --- a/src/werkzeug/http.py +++ b/src/werkzeug/http.py @@ -361,6 +361,10 @@ def parse_dict_header(value: str) -> dict[str, str | None]: key, has_value, value = item.partition("=") key = key.strip() + if not key: + # =value is not valid + continue + if not has_value: result[key] = None continue @@ -395,22 +399,8 @@ def parse_dict_header(value: str) -> dict[str, str | None]: # https://httpwg.org/specs/rfc9110.html#parameter -_parameter_re = re.compile( - r""" - # don't match multiple empty parts, that causes backtracking - \s*;\s* # find the part delimiter - (?: - ([\w!#$%&'*+\-.^`|~]+) # key, one or more token chars - = # equals, with no space on either side - ( # value, token or quoted string - [\w!#$%&'*+\-.^`|~]+ # one or more token chars - | - "(?:\\\\|\\"|.)*?" # quoted string, consuming slash escapes - ) - )? # optionally match key=value, to account for empty parts - """, - re.ASCII | re.VERBOSE, -) +_parameter_key_re = re.compile(r"([\w!#$%&'*+\-.^`|~]+)=", flags=re.ASCII) +_parameter_token_value_re = re.compile(r"[\w!#$%&'*+\-.^`|~]+", flags=re.ASCII) # https://www.rfc-editor.org/rfc/rfc2231#section-4 _charset_value_re = re.compile( r""" @@ -492,18 +482,49 @@ def parse_options_header(value: str | None) -> tuple[str, dict[str, str]]: # empty (invalid) value, or value without options return value, {} - rest = f";{rest}" + # Collect all valid key=value parts without processing the value. + parts: list[tuple[str, str]] = [] + + while True: + if (m := _parameter_key_re.match(rest)) is not None: + pk = m.group(1).lower() + rest = rest[m.end() :] + + # Value may be a token. + if (m := _parameter_token_value_re.match(rest)) is not None: + parts.append((pk, m.group())) + + # Value may be a quoted string, find the closing quote. + elif rest[:1] == '"': + pos = 1 + length = len(rest) + + while pos < length: + if rest[pos : pos + 2] in {"\\\\", '\\"'}: + # Consume escaped slashes and quotes. + pos += 2 + elif rest[pos] == '"': + # Stop at an unescaped quote. + parts.append((pk, rest[: pos + 1])) + rest = rest[pos + 1 :] + break + else: + # Consume any other character. + pos += 1 + + # Find the next section delimited by `;`, if any. + if (end := rest.find(";")) == -1: + break + + rest = rest[end + 1 :].lstrip() + options: dict[str, str] = {} encoding: str | None = None continued_encoding: str | None = None - for pk, pv in _parameter_re.findall(rest): - if not pk: - # empty or invalid part - continue - - pk = pk.lower() - + # For each collected part, process optional charset and continuation, + # unquote quoted values. + for pk, pv in parts: if pk[-1] == "*": # key*=charset''value becomes key=value, where value is percent encoded pk = pk[:-1] @@ -578,7 +599,7 @@ def parse_accept_header( Parse according to RFC 9110. Items with invalid ``q`` values are skipped. """ if cls is None: - cls = t.cast(t.Type[_TAnyAccept], ds.Accept) + cls = t.cast(type[_TAnyAccept], ds.Accept) if not value: return cls(None) @@ -893,6 +914,10 @@ def quote_etag(etag: str, weak: bool = False) -> str: return etag +@t.overload +def unquote_etag(etag: str) -> tuple[str, bool]: ... +@t.overload +def unquote_etag(etag: None) -> tuple[None, None]: ... def unquote_etag( etag: str | None, ) -> tuple[str, bool] | tuple[None, None]: @@ -1214,6 +1239,7 @@ def dump_cookie( sync_expires: bool = True, max_size: int = 4093, samesite: str | None = None, + partitioned: bool = False, ) -> str: """Create a Set-Cookie header without the ``Set-Cookie`` prefix. @@ -1250,9 +1276,14 @@ def dump_cookie( `_. Set to 0 to disable this check. :param samesite: Limits the scope of the cookie such that it will only be attached to requests if those requests are same-site. + :param partitioned: Opts the cookie into partitioned storage. This + will also set secure to True .. _`cookie`: http://browsercookielimits.squawky.net/ + .. versionchanged:: 3.1 + The ``partitioned`` parameter was added. + .. versionchanged:: 3.0 Passing bytes, and the ``charset`` parameter, were removed. @@ -1296,6 +1327,9 @@ def dump_cookie( if samesite not in {"Strict", "Lax", "None"}: raise ValueError("SameSite must be 'Strict', 'Lax', or 'None'.") + if partitioned: + secure = True + # Quote value if it contains characters not allowed by RFC 6265. Slash-escape with # three octal digits, which matches http.cookies, although the RFC suggests base64. if not _cookie_no_quote_re.fullmatch(value): @@ -1317,6 +1351,7 @@ def dump_cookie( ("HttpOnly", httponly), ("Path", path), ("SameSite", samesite), + ("Partitioned", partitioned), ): if v is None or v is False: continue diff --git a/src/werkzeug/middleware/lint.py b/src/werkzeug/middleware/lint.py index de93b52..3714271 100644 --- a/src/werkzeug/middleware/lint.py +++ b/src/werkzeug/middleware/lint.py @@ -435,5 +435,5 @@ def checking_start_response( app_iter = self.app(environ, t.cast("StartResponse", checking_start_response)) self.check_iterator(app_iter) return GuardedIterator( - app_iter, t.cast(t.Tuple[int, Headers], headers_set), chunks + app_iter, t.cast(tuple[int, Headers], headers_set), chunks ) diff --git a/src/werkzeug/middleware/shared_data.py b/src/werkzeug/middleware/shared_data.py index 0a0c956..c7c06df 100644 --- a/src/werkzeug/middleware/shared_data.py +++ b/src/werkzeug/middleware/shared_data.py @@ -11,6 +11,7 @@ from __future__ import annotations +import collections.abc as cabc import importlib.util import mimetypes import os @@ -29,8 +30,8 @@ from ..wsgi import get_path_info from ..wsgi import wrap_file -_TOpener = t.Callable[[], t.Tuple[t.IO[bytes], datetime, int]] -_TLoader = t.Callable[[t.Optional[str]], t.Tuple[t.Optional[str], t.Optional[_TOpener]]] +_TOpener = t.Callable[[], tuple[t.IO[bytes], datetime, int]] +_TLoader = t.Callable[[t.Optional[str]], tuple[t.Optional[str], t.Optional[_TOpener]]] if t.TYPE_CHECKING: from _typeshed.wsgi import StartResponse @@ -103,7 +104,7 @@ def __init__( self, app: WSGIApplication, exports: ( - dict[str, str | tuple[str, str]] + cabc.Mapping[str, str | tuple[str, str]] | t.Iterable[tuple[str, str | tuple[str, str]]] ), disallow: None = None, @@ -116,7 +117,7 @@ def __init__( self.cache = cache self.cache_timeout = cache_timeout - if isinstance(exports, dict): + if isinstance(exports, cabc.Mapping): exports = exports.items() for key, value in exports: diff --git a/src/werkzeug/routing/rules.py b/src/werkzeug/routing/rules.py index 6a02f8d..2dad31d 100644 --- a/src/werkzeug/routing/rules.py +++ b/src/werkzeug/routing/rules.py @@ -101,7 +101,7 @@ def _pythonize(value: str) -> None | bool | int | float | str: return _PYTHON_CONSTANTS[value] for convert in int, float: try: - return convert(value) # type: ignore + return convert(value) except ValueError: pass if value[:1] == value[-1:] and value[0] in "\"'": @@ -294,11 +294,18 @@ def get_rules(self, map: Map) -> t.Iterator[Rule]: ) -def _prefix_names(src: str) -> ast.stmt: +_ASTT = t.TypeVar("_ASTT", bound=ast.AST) + + +def _prefix_names(src: str, expected_type: type[_ASTT]) -> _ASTT: """ast parse and prefix names with `.` to avoid collision with user vars""" - tree = ast.parse(src).body[0] + tree: ast.AST = ast.parse(src).body[0] if isinstance(tree, ast.Expr): - tree = tree.value # type: ignore + tree = tree.value + if not isinstance(tree, expected_type): + raise TypeError( + f"AST node is of type {type(tree).__name__}, not {expected_type.__name__}" + ) for node in ast.walk(tree): if isinstance(node, ast.Name): node.id = f".{node.id}" @@ -313,8 +320,11 @@ def _prefix_names(src: str) -> ast.stmt: else: q = params = "" """ -_IF_KWARGS_URL_ENCODE_AST = _prefix_names(_IF_KWARGS_URL_ENCODE_CODE) -_URL_ENCODE_AST_NAMES = (_prefix_names("q"), _prefix_names("params")) +_IF_KWARGS_URL_ENCODE_AST = _prefix_names(_IF_KWARGS_URL_ENCODE_CODE, ast.If) +_URL_ENCODE_AST_NAMES = ( + _prefix_names("q", ast.Name), + _prefix_names("params", ast.Name), +) class Rule(RuleFactory): @@ -751,13 +761,13 @@ def _compile_builder( else: opl.append((True, data)) - def _convert(elem: str) -> ast.stmt: - ret = _prefix_names(_CALL_CONVERTER_CODE_FMT.format(elem=elem)) - ret.args = [ast.Name(str(elem), ast.Load())] # type: ignore # str for py2 + def _convert(elem: str) -> ast.Call: + ret = _prefix_names(_CALL_CONVERTER_CODE_FMT.format(elem=elem), ast.Call) + ret.args = [ast.Name(elem, ast.Load())] return ret - def _parts(ops: list[tuple[bool, str]]) -> list[ast.AST]: - parts = [ + def _parts(ops: list[tuple[bool, str]]) -> list[ast.expr]: + parts: list[ast.expr] = [ _convert(elem) if is_dynamic else ast.Constant(elem) for is_dynamic, elem in ops ] @@ -773,13 +783,14 @@ def _parts(ops: list[tuple[bool, str]]) -> list[ast.AST]: dom_parts = _parts(dom_ops) url_parts = _parts(url_ops) + body: list[ast.stmt] if not append_unknown: body = [] else: body = [_IF_KWARGS_URL_ENCODE_AST] url_parts.extend(_URL_ENCODE_AST_NAMES) - def _join(parts: list[ast.AST]) -> ast.AST: + def _join(parts: list[ast.expr]) -> ast.expr: if len(parts) == 1: # shortcut return parts[0] return ast.JoinedStr(parts) @@ -795,7 +806,7 @@ def _join(parts: list[ast.AST]) -> ast.AST: ] kargs = [str(k) for k in defaults] - func_ast: ast.FunctionDef = _prefix_names("def _(): pass") # type: ignore + func_ast = _prefix_names("def _(): pass", ast.FunctionDef) func_ast.name = f"" func_ast.args.args.append(ast.arg(".self", None)) for arg in pargs + kargs: @@ -815,13 +826,13 @@ def _join(parts: list[ast.AST]) -> ast.AST: # bad line numbers cause an assert to fail in debug builds for node in ast.walk(module): if "lineno" in node._attributes: - node.lineno = 1 + node.lineno = 1 # type: ignore[attr-defined] if "end_lineno" in node._attributes: - node.end_lineno = node.lineno + node.end_lineno = node.lineno # type: ignore[attr-defined] if "col_offset" in node._attributes: - node.col_offset = 0 + node.col_offset = 0 # type: ignore[attr-defined] if "end_col_offset" in node._attributes: - node.end_col_offset = node.col_offset + node.end_col_offset = node.col_offset # type: ignore[attr-defined] code = compile(module, "", "exec") return self._get_func_code(code, func_ast.name) diff --git a/src/werkzeug/sansio/http.py b/src/werkzeug/sansio/http.py index b2b8877..f02d7fd 100644 --- a/src/werkzeug/sansio/http.py +++ b/src/werkzeug/sansio/http.py @@ -72,7 +72,6 @@ def is_resource_modified( if etag: etag, _ = unquote_etag(etag) - etag = t.cast(str, etag) if if_range is not None and if_range.etag is not None: unmodified = parse_etags(if_range.etag).contains(etag) diff --git a/src/werkzeug/sansio/multipart.py b/src/werkzeug/sansio/multipart.py index fc87353..731be03 100644 --- a/src/werkzeug/sansio/multipart.py +++ b/src/werkzeug/sansio/multipart.py @@ -140,6 +140,8 @@ def receive_data(self, data: bytes | None) -> None: self.max_form_memory_size is not None and len(self.buffer) + len(data) > self.max_form_memory_size ): + # Ensure that data within single event does not exceed limit. + # Also checked across accumulated events in MultiPartParser. raise RequestEntityTooLarge() else: self.buffer.extend(data) diff --git a/src/werkzeug/sansio/request.py b/src/werkzeug/sansio/request.py index dd0805d..8d5fbd8 100644 --- a/src/werkzeug/sansio/request.py +++ b/src/werkzeug/sansio/request.py @@ -67,10 +67,8 @@ class Request: #: the class to use for `args` and `form`. The default is an #: :class:`~werkzeug.datastructures.ImmutableMultiDict` which supports - #: multiple values per key. alternatively it makes sense to use an - #: :class:`~werkzeug.datastructures.ImmutableOrderedMultiDict` which - #: preserves order or a :class:`~werkzeug.datastructures.ImmutableDict` - #: which is the fastest but only remembers the last key. It is also + #: multiple values per key. A :class:`~werkzeug.datastructures.ImmutableDict` + #: is faster but only remembers the last key. It is also #: possible to use mutable structures, but this is not recommended. #: #: .. versionadded:: 0.6 diff --git a/src/werkzeug/sansio/response.py b/src/werkzeug/sansio/response.py index 9093b0a..9fed086 100644 --- a/src/werkzeug/sansio/response.py +++ b/src/werkzeug/sansio/response.py @@ -197,6 +197,7 @@ def set_cookie( secure: bool = False, httponly: bool = False, samesite: str | None = None, + partitioned: bool = False, ) -> None: """Sets a cookie. @@ -221,6 +222,10 @@ def set_cookie( :param httponly: Disallow JavaScript access to the cookie. :param samesite: Limit the scope of the cookie to only be attached to requests that are "same-site". + :param partitioned: If ``True``, the cookie will be partitioned. + + .. versionchanged:: 3.1 + The ``partitioned`` parameter was added. """ self.headers.add( "Set-Cookie", @@ -235,6 +240,7 @@ def set_cookie( httponly=httponly, max_size=self.max_cookie_size, samesite=samesite, + partitioned=partitioned, ), ) @@ -246,6 +252,7 @@ def delete_cookie( secure: bool = False, httponly: bool = False, samesite: str | None = None, + partitioned: bool = False, ) -> None: """Delete a cookie. Fails silently if key doesn't exist. @@ -259,6 +266,7 @@ def delete_cookie( :param httponly: Disallow JavaScript access to the cookie. :param samesite: Limit the scope of the cookie to only be attached to requests that are "same-site". + :param partitioned: If ``True``, the cookie will be partitioned. """ self.set_cookie( key, @@ -269,6 +277,7 @@ def delete_cookie( secure=secure, httponly=httponly, samesite=samesite, + partitioned=partitioned, ) @property diff --git a/src/werkzeug/sansio/utils.py b/src/werkzeug/sansio/utils.py index 14fa0ac..ff7ceda 100644 --- a/src/werkzeug/sansio/utils.py +++ b/src/werkzeug/sansio/utils.py @@ -71,6 +71,9 @@ def get_host( :return: Host, with port if necessary. :raise ~werkzeug.exceptions.SecurityError: If the host is not trusted. + + .. versionchanged:: 3.1.3 + If ``SERVER_NAME`` is IPv6, it is wrapped in ``[]``. """ host = "" @@ -79,6 +82,11 @@ def get_host( elif server is not None: host = server[0] + # If SERVER_NAME is IPv6, wrap it in [] to match Host header. + # Check for : because domain or IPv4 can't have that. + if ":" in host and host[0] != "[": + host = f"[{host}]" + if server[1] is not None: host = f"{host}:{server[1]}" diff --git a/src/werkzeug/security.py b/src/werkzeug/security.py index 9999509..3f49ad1 100644 --- a/src/werkzeug/security.py +++ b/src/werkzeug/security.py @@ -7,7 +7,7 @@ import secrets SALT_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" -DEFAULT_PBKDF2_ITERATIONS = 600000 +DEFAULT_PBKDF2_ITERATIONS = 1_000_000 _os_alt_seps: list[str] = list( sep for sep in [os.sep, os.path.altsep] if sep is not None and sep != "/" @@ -92,6 +92,9 @@ def generate_password_hash( :param method: The key derivation function and parameters. :param salt_length: The number of characters to generate for the salt. + .. versionchanged:: 3.1 + The default iterations for pbkdf2 was increased to 1,000,000. + .. versionchanged:: 2.3 Scrypt support was added. @@ -151,6 +154,8 @@ def safe_join(directory: str, *pathnames: str) -> str | None: if ( any(sep in filename for sep in _os_alt_seps) or os.path.isabs(filename) + # ntpath.isabs doesn't catch this on Python < 3.11 + or filename.startswith("/") or filename == ".." or filename.startswith("../") ): diff --git a/src/werkzeug/serving.py b/src/werkzeug/serving.py index 859f9aa..ec16640 100644 --- a/src/werkzeug/serving.py +++ b/src/werkzeug/serving.py @@ -37,6 +37,12 @@ try: import ssl + + connection_dropped_errors: tuple[type[Exception], ...] = ( + ConnectionError, + socket.timeout, + ssl.SSLEOFError, + ) except ImportError: class _SslDummy: @@ -47,6 +53,7 @@ def __getattr__(self, name: str) -> t.Any: ) ssl = _SslDummy() # type: ignore + connection_dropped_errors = (ConnectionError, socket.timeout) _log_add_style = True @@ -74,7 +81,7 @@ class ForkingMixIn: # type: ignore LISTEN_QUEUE = 128 _TSSLContextArg = t.Optional[ - t.Union["ssl.SSLContext", t.Tuple[str, t.Optional[str]], t.Literal["adhoc"]] + t.Union["ssl.SSLContext", tuple[str, t.Optional[str]], t.Literal["adhoc"]] ] if t.TYPE_CHECKING: @@ -361,7 +368,7 @@ def execute(app: WSGIApplication) -> None: try: execute(self.server.app) - except (ConnectionError, socket.timeout) as e: + except connection_dropped_errors as e: self.connection_dropped(e, environ) except Exception as e: if self.server.passthrough_errors: @@ -466,9 +473,11 @@ def log_message(self, format: str, *args: t.Any) -> None: self.log("info", format, *args) def log(self, type: str, message: str, *args: t.Any) -> None: + # an IPv6 scoped address contains "%" which breaks logging + address_string = self.address_string().replace("%", "%%") _log( type, - f"{self.address_string()} - - [{self.log_date_time_string()}] {message}\n", + f"{address_string} - - [{self.log_date_time_string()}] {message}\n", *args, ) diff --git a/src/werkzeug/test.py b/src/werkzeug/test.py index 38f69bf..5c3c608 100644 --- a/src/werkzeug/test.py +++ b/src/werkzeug/test.py @@ -656,7 +656,7 @@ def close(self) -> None: try: files = self.files.values() except AttributeError: - files = () # type: ignore + files = () for f in files: try: f.close() @@ -818,7 +818,7 @@ def __init__( {}, ) - self.response_wrapper = t.cast(t.Type["TestResponse"], response_wrapper) + self.response_wrapper = t.cast(type["TestResponse"], response_wrapper) if use_cookies: self._cookies: dict[tuple[str, str, str], Cookie] | None = {} @@ -1431,7 +1431,7 @@ def _to_request_header(self) -> str: def _from_response_header(cls, server_name: str, path: str, header: str) -> te.Self: header, _, parameters_str = header.partition(";") key, _, value = header.partition("=") - decoded_key, decoded_value = next(parse_cookie(header).items()) + decoded_key, decoded_value = next(parse_cookie(header).items()) # type: ignore[call-overload] params = {} for item in parameters_str.split(";"): diff --git a/src/werkzeug/utils.py b/src/werkzeug/utils.py index 59b97b7..3d3bbf0 100644 --- a/src/werkzeug/utils.py +++ b/src/werkzeug/utils.py @@ -150,7 +150,7 @@ def lookup(self, obj: Request) -> WSGIEnvironment: class header_property(_DictAccessorProperty[_TAccessorValue]): """Like `environ_property` but for headers.""" - def lookup(self, obj: Request | Response) -> Headers: + def lookup(self, obj: Request | Response) -> Headers: # type: ignore[override] return obj.headers diff --git a/src/werkzeug/wrappers/request.py b/src/werkzeug/wrappers/request.py index 38053c2..719a3bc 100644 --- a/src/werkzeug/wrappers/request.py +++ b/src/werkzeug/wrappers/request.py @@ -84,8 +84,11 @@ class Request(_SansIORequest): #: data in memory for post data is longer than the specified value a #: :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised. #: + #: .. versionchanged:: 3.1 + #: Defaults to 500kB instead of unlimited. + #: #: .. versionadded:: 0.5 - max_form_memory_size: int | None = None + max_form_memory_size: int | None = 500_000 #: The maximum number of multipart parts to parse, passed to #: :attr:`form_data_parser_class`. Parsing form data with more than this @@ -370,7 +373,7 @@ def data(self) -> bytes: return self.get_data(parse_form_data=True) @t.overload - def get_data( # type: ignore + def get_data( self, cache: bool = True, as_text: t.Literal[False] = False, diff --git a/tests/conftest.py b/tests/conftest.py index b73202c..f05fd84 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,55 +1,149 @@ +from __future__ import annotations + +import collections.abc as cabc import http.client import json import os import socket import ssl +import subprocess import sys +import time +import typing as t +from contextlib import closing +from contextlib import ExitStack from pathlib import Path +from types import TracebackType import ephemeral_port_reserve import pytest -from xprocess import ProcessStarter - -from werkzeug.utils import cached_property -run_path = str(Path(__file__).parent / "live_apps" / "run.py") +if t.TYPE_CHECKING: + import typing_extensions as te class UnixSocketHTTPConnection(http.client.HTTPConnection): - def connect(self): + def connect(self) -> None: self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + # Raises FileNotFoundError if the server hasn't started yet. self.sock.connect(self.host) +# Used to annotate the ``DevServerClient.request`` return value. +class DataHTTPResponse(http.client.HTTPResponse): + data: bytes + json: t.Any + + class DevServerClient: - def __init__(self, kwargs): - host = kwargs.get("hostname", "127.0.0.1") + """Manage a live dev server process and make requests to it. Must be used + as a context manager. + + If ``hostname`` starts with ``unix://``, the server listens to a unix socket + file instead of a TCP socket. + + If ``port`` is not given, a random port is reserved for use by the server, + to allow multiple servers to run simultaneously. + + If ``ssl_context`` is given, the server listens with TLS enabled. It can be + the special value ``custom`` to generate and pass a context to + ``run_simple``, as opposed to ``adhoc`` which tells ``run_simple`` to + generate the context. + + :param app_name: The name of the app from the ``live_apps`` folder to load. + :param tmp_path: The current test's temporary directory. The server process + sets the working dir here, it is added to the Python path, the log file + is written here, and for unix connections the socket is opened here. + :param server_kwargs: Arguments to pass to ``live_apps/run.py`` to control + how ``run_simple`` is called in the subprocess. + """ - if not host.startswith("unix"): - port = kwargs.get("port") + scheme: str + """One of ``http``, ``https``, or ``unix``. Set based on ``ssl_context`` or + ``hostname``. + """ + addr: str + """The host and port.""" + url: str + """The scheme, host, and port.""" + + def __init__( + self, app_name: str = "standard", *, tmp_path: Path, **server_kwargs: t.Any + ) -> None: + host = server_kwargs.get("hostname", "127.0.0.1") + + if not host.startswith("unix://"): + port = server_kwargs.get("port") if port is None: - kwargs["port"] = port = ephemeral_port_reserve.reserve(host) + server_kwargs["port"] = port = ephemeral_port_reserve.reserve(host) - scheme = "https" if "ssl_context" in kwargs else "http" + self.scheme = "https" if "ssl_context" in server_kwargs else "http" self.addr = f"{host}:{port}" - self.url = f"{scheme}://{self.addr}" + self.url = f"{self.scheme}://{self.addr}" else: + self.scheme = "unix" self.addr = host[7:] # strip "unix://" self.url = host - self.log = None - - def tail_log(self, path): - # surrogateescape allows for handling of file streams - # containing junk binary values as normal text streams - self.log = open(path, errors="surrogateescape") - self.log.read() - - def connect(self, **kwargs): - protocol = self.url.partition(":")[0] - - if protocol == "https": + self._app_name = app_name + self._server_kwargs = server_kwargs + self._tmp_path = tmp_path + self._log_write: t.IO[bytes] | None = None + self._log_read: t.IO[str] | None = None + self._proc: subprocess.Popen[bytes] | None = None + + def __enter__(self) -> te.Self: + """Start the server process and wait for it to be ready.""" + log_path = self._tmp_path / "log.txt" + self._log_write = open(log_path, "wb") + self._log_read = open(log_path, encoding="utf8", errors="surrogateescape") + tmp_dir = os.fspath(self._tmp_path) + self._proc = subprocess.Popen( + [ + sys.executable, + os.fspath(Path(__file__).parent / "live_apps/run.py"), + self._app_name, + json.dumps(self._server_kwargs), + ], + env={**os.environ, "PYTHONUNBUFFERED": "1", "PYTHONPATH": tmp_dir}, + cwd=tmp_dir, + close_fds=True, + stdout=self._log_write, + stderr=subprocess.STDOUT, + ) + self.wait_ready() + return self + + def __exit__( + self, + exc_type: type[BaseException], + exc_val: BaseException, + exc_tb: TracebackType, + ) -> None: + """Clean up the server process.""" + assert self._proc is not None + self._proc.terminate() + self._proc.wait() + self._proc = None + assert self._log_read is not None + self._log_read.close() + self._log_read = None + assert self._log_write is not None + self._log_write.close() + self._log_write = None + + def connect(self, **kwargs: t.Any) -> http.client.HTTPConnection: + """Create a connection to the server, without sending a request. + Useful if a test requires lower level methods to try something that + ``HTTPClient.request`` will not do. + + If the server's scheme is HTTPS and the TLS ``context`` argument is not + given, a default permissive context is used. + + :param kwargs: Arguments to :class:`http.client.HTTPConnection`. + """ + if self.scheme == "https": if "context" not in kwargs: context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) context.check_hostname = False @@ -58,21 +152,31 @@ def connect(self, **kwargs): return http.client.HTTPSConnection(self.addr, **kwargs) - if protocol == "unix": + if self.scheme == "unix": return UnixSocketHTTPConnection(self.addr, **kwargs) return http.client.HTTPConnection(self.addr, **kwargs) - def request(self, path="", **kwargs): + def request(self, url: str = "", **kwargs: t.Any) -> DataHTTPResponse: + """Open a connection and make a request to the server, returning the + response. + + The response object ``data`` parameter has the result of + ``response.read()``. If the response has a ``application/json`` content + type, the ``json`` parameter is populated with ``json.loads(data)``. + + :param url: URL to put in the request line. + :param kwargs: Arguments to :meth:`http.client.HTTPConnection.request`. + """ kwargs.setdefault("method", "GET") - kwargs.setdefault("url", path) - conn = self.connect() - conn.request(**kwargs) + kwargs["url"] = url + response: DataHTTPResponse - with conn.getresponse() as response: - response.data = response.read() + with closing(self.connect()) as conn: + conn.request(**kwargs) - conn.close() + with conn.getresponse() as response: # type: ignore[assignment] + response.data = response.read() if response.headers.get("Content-Type", "").startswith("application/json"): response.json = json.loads(response.data) @@ -81,53 +185,66 @@ def request(self, path="", **kwargs): return response - def wait_for_log(self, start): + def wait_ready(self) -> None: + """Wait until a request to ``/ensure`` is successful, indicating the + server has started and is listening. + """ while True: - for line in self.log: - if line.startswith(start): - return + try: + self.request("/ensure") + return + # ConnectionRefusedError for http, FileNotFoundError for unix + except (ConnectionRefusedError, FileNotFoundError): + time.sleep(0.1) - def wait_for_reload(self): - self.wait_for_log(" * Restarting with ") + def read_log(self) -> str: + """Read from the current position to the current end of the log.""" + assert self._log_read is not None + return self._log_read.read() + def wait_for_log(self, value: str) -> None: + """Wait until a line in the log contains the given string. -@pytest.fixture() -def dev_server(xprocess, request, tmp_path): - """A function that will start a dev server in an external process - and return a client for interacting with the server. - """ + :param value: The string to search for. + """ + assert self._log_read is not None - def start_dev_server(name="standard", **kwargs): - client = DevServerClient(kwargs) + while True: + for line in self._log_read: + if value in line: + return + + time.sleep(0.1) + + def wait_for_reload(self) -> None: + """Wait until the server logs that it is restarting, then wait for it to + be ready. + """ + self.wait_for_log("Restarting with") + self.wait_ready() - class Starter(ProcessStarter): - args = [sys.executable, run_path, name, json.dumps(kwargs)] - # Extend the existing env, otherwise Windows and CI fails. - # Modules will be imported from tmp_path for the reloader. - # Unbuffered output so the logs update immediately. - env = {**os.environ, "PYTHONPATH": str(tmp_path), "PYTHONUNBUFFERED": "1"} - @cached_property - def pattern(self): - client.request("/ensure") - return "GET /ensure" +class StartDevServer(t.Protocol): + def __call__(self, name: str = "standard", **kwargs: t.Any) -> DevServerClient: ... - # Each test that uses the fixture will have a different log. - xp_name = f"dev_server-{request.node.name}" - _, log_path = xprocess.ensure(xp_name, Starter, restart=True) - client.tail_log(log_path) - @request.addfinalizer - def close(): - xprocess.getinfo(xp_name).terminate() - client.log.close() +@pytest.fixture() +def dev_server(tmp_path: Path) -> cabc.Iterator[StartDevServer]: + """A function that will start a dev server in a subprocess and return a + client for interacting with the server. + """ + exit_stack = ExitStack() + def start_dev_server(name: str = "standard", **kwargs: t.Any) -> DevServerClient: + client = DevServerClient(name, tmp_path=tmp_path, **kwargs) + exit_stack.enter_context(client) # type: ignore[arg-type] return client - return start_dev_server + with exit_stack: + yield start_dev_server @pytest.fixture() -def standard_app(dev_server): +def standard_app(dev_server: t.Callable[..., DevServerClient]) -> DevServerClient: """Equivalent to ``dev_server("standard")``.""" return dev_server() diff --git a/tests/live_apps/run.py b/tests/live_apps/run.py index aacdcb6..1371e67 100644 --- a/tests/live_apps/run.py +++ b/tests/live_apps/run.py @@ -4,6 +4,7 @@ from werkzeug.serving import generate_adhoc_ssl_context from werkzeug.serving import run_simple +from werkzeug.serving import WSGIRequestHandler from werkzeug.wrappers import Request from werkzeug.wrappers import Response @@ -23,10 +24,14 @@ def app(request): kwargs.update(hostname="127.0.0.1", port=5000, application=app) kwargs.update(json.loads(sys.argv[2])) ssl_context = kwargs.get("ssl_context") +override_client_addr = kwargs.pop("override_client_addr", None) if ssl_context == "custom": kwargs["ssl_context"] = generate_adhoc_ssl_context() elif isinstance(ssl_context, list): kwargs["ssl_context"] = tuple(ssl_context) +if override_client_addr: + WSGIRequestHandler.address_string = lambda _: override_client_addr + run_simple(**kwargs) diff --git a/tests/middleware/test_http_proxy.py b/tests/middleware/test_http_proxy.py index a1497c5..5e1f005 100644 --- a/tests/middleware/test_http_proxy.py +++ b/tests/middleware/test_http_proxy.py @@ -5,7 +5,6 @@ from werkzeug.wrappers import Response -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server def test_http_proxy(standard_app): app = ProxyMiddleware( diff --git a/tests/sansio/test_utils.py b/tests/sansio/test_utils.py index d43de66..a63e7c6 100644 --- a/tests/sansio/test_utils.py +++ b/tests/sansio/test_utils.py @@ -14,12 +14,16 @@ ("https", "spam", None, "spam"), ("https", "spam:443", None, "spam"), ("http", "spam:8080", None, "spam:8080"), + ("http", "127.0.0.1:8080", None, "127.0.0.1:8080"), + ("http", "[::1]:8080", None, "[::1]:8080"), ("ws", "spam", None, "spam"), ("ws", "spam:80", None, "spam"), ("wss", "spam", None, "spam"), ("wss", "spam:443", None, "spam"), ("http", None, ("spam", 80), "spam"), ("http", None, ("spam", 8080), "spam:8080"), + ("http", None, ("127.0.0.1", 8080), "127.0.0.1:8080"), + ("http", None, ("::1", 8080), "[::1]:8080"), ("http", None, ("unix/socket", None), "unix/socket"), ("http", "spam", ("eggs", 80), "spam"), ], diff --git a/tests/test_datastructures.py b/tests/test_datastructures.py index 64330e1..0cd4974 100644 --- a/tests/test_datastructures.py +++ b/tests/test_datastructures.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import io import pickle import tempfile @@ -10,6 +12,8 @@ from werkzeug import datastructures as ds from werkzeug import http +from werkzeug.datastructures.structures import _ImmutableOrderedMultiDict +from werkzeug.datastructures.structures import _OrderedMultiDict from werkzeug.exceptions import BadRequestKeyError @@ -42,7 +46,7 @@ def items(self, multi=1): class _MutableMultiDictTests: - storage_class: t.Type["ds.MultiDict"] + storage_class: type[ds.MultiDict] def test_pickle(self): cls = self.storage_class @@ -257,9 +261,20 @@ def test_basic_interface(self): md.setlist("foo", [1, 2]) assert md.getlist("foo") == [1, 2] + def test_or(self) -> None: + a = self.storage_class({"x": 1}) + b = a | {"y": 2} + assert isinstance(b, self.storage_class) + assert "x" in b and "y" in b + + def test_ior(self) -> None: + a = self.storage_class({"x": 1}) + a |= {"y": 2} + assert "x" in a and "y" in a + class _ImmutableDictTests: - storage_class: t.Type[dict] + storage_class: type[dict] def test_follows_dict_interface(self): cls = self.storage_class @@ -304,6 +319,17 @@ def test_dict_is_hashable(self): assert immutable in x assert immutable2 in x + def test_or(self) -> None: + a = self.storage_class({"x": 1}) + b = a | {"y": 2} + assert "x" in b and "y" in b + + def test_ior(self) -> None: + a = self.storage_class({"x": 1}) + + with pytest.raises(TypeError): + a |= {"y": 2} + class TestImmutableTypeConversionDict(_ImmutableDictTests): storage_class = ds.ImmutableTypeConversionDict @@ -334,8 +360,9 @@ class TestImmutableDict(_ImmutableDictTests): storage_class = ds.ImmutableDict +@pytest.mark.filterwarnings("ignore:'OrderedMultiDict':DeprecationWarning") class TestImmutableOrderedMultiDict(_ImmutableDictTests): - storage_class = ds.ImmutableOrderedMultiDict + storage_class = _ImmutableOrderedMultiDict def test_ordered_multidict_is_hashable(self): a = self.storage_class([("a", 1), ("b", 1), ("a", 2)]) @@ -413,8 +440,9 @@ def test_getitem_raise_badrequestkeyerror_for_empty_list_value(self): md["empty"] +@pytest.mark.filterwarnings("ignore:'OrderedMultiDict':DeprecationWarning") class TestOrderedMultiDict(_MutableMultiDictTests): - storage_class = ds.OrderedMultiDict + storage_class = _OrderedMultiDict def test_ordered_interface(self): cls = self.storage_class @@ -796,6 +824,17 @@ def test_equality(self): assert h1 == h2 + def test_or(self) -> None: + a = ds.Headers({"x": 1}) + b = a | {"y": 2} + assert isinstance(b, ds.Headers) + assert "x" in b and "y" in b + + def test_ior(self) -> None: + a = ds.Headers({"x": 1}) + a |= {"y": 2} + assert "x" in a and "y" in a + class TestEnvironHeaders: storage_class = ds.EnvironHeaders @@ -837,6 +876,22 @@ def test_return_type_is_str(self): assert headers["Foo"] == "\xe2\x9c\x93" assert next(iter(headers)) == ("Foo", "\xe2\x9c\x93") + def test_or(self) -> None: + headers = ds.EnvironHeaders({"x": "1"}) + + with pytest.raises(TypeError): + headers | {"y": "2"} + + def test_ior(self) -> None: + headers = ds.EnvironHeaders({}) + + with pytest.raises(TypeError): + headers |= {"y": "2"} + + def test_str(self) -> None: + headers = ds.EnvironHeaders({"CONTENT_LENGTH": "50", "HTTP_HOST": "test"}) + assert str(headers) == "Content-Length: 50\r\nHost: test\r\n\r\n" + class TestHeaderSet: storage_class = ds.HeaderSet @@ -924,7 +979,7 @@ def test_callback_dict_writes(self): assert_calls, func = make_call_asserter() initial = {"a": "foo", "b": "bar"} dct = self.storage_class(initial=initial, on_update=func) - with assert_calls(8, "callback not triggered by write method"): + with assert_calls(9, "callback not triggered by write method"): # always-write methods dct["z"] = 123 dct["z"] = 123 # must trigger again @@ -934,6 +989,7 @@ def test_callback_dict_writes(self): dct.popitem() dct.update([]) dct.clear() + dct |= {} with assert_calls(0, "callback triggered by failed del"): pytest.raises(KeyError, lambda: dct.__delitem__("x")) with assert_calls(0, "callback triggered by failed pop"): @@ -951,7 +1007,39 @@ def test_set_none(self): cc.no_cache = None assert cc.no_cache is None cc.no_cache = False - assert cc.no_cache is False + assert cc.no_cache is None + + def test_no_transform(self): + cc = ds.RequestCacheControl([("no-transform", None)]) + assert cc.no_transform is True + cc = ds.RequestCacheControl() + assert cc.no_transform is False + + def test_min_fresh(self): + cc = ds.RequestCacheControl([("min-fresh", "0")]) + assert cc.min_fresh == 0 + cc = ds.RequestCacheControl([("min-fresh", None)]) + assert cc.min_fresh is None + cc = ds.RequestCacheControl() + assert cc.min_fresh is None + + def test_must_understand(self): + cc = ds.ResponseCacheControl([("must-understand", None)]) + assert cc.must_understand is True + cc = ds.ResponseCacheControl() + assert cc.must_understand is False + + def test_stale_while_revalidate(self): + cc = ds.ResponseCacheControl([("stale-while-revalidate", "1")]) + assert cc.stale_while_revalidate == 1 + cc = ds.ResponseCacheControl() + assert cc.stale_while_revalidate is None + + def test_stale_if_error(self): + cc = ds.ResponseCacheControl([("stale-if-error", "1")]) + assert cc.stale_if_error == 1 + cc = ds.ResponseCacheControl() + assert cc.stale_while_revalidate is None class TestContentSecurityPolicy: @@ -1195,3 +1283,15 @@ def test_range_to_header(ranges): def test_range_validates_ranges(ranges): with pytest.raises(ValueError): ds.Range("bytes", ranges) + + +@pytest.mark.parametrize( + ("value", "expect"), + [ + ({"a": "ab"}, [("a", "ab")]), + ({"a": ["a", "b"]}, [("a", "a"), ("a", "b")]), + ({"a": b"ab"}, [("a", b"ab")]), + ], +) +def test_iter_multi_data(value: t.Any, expect: list[tuple[t.Any, t.Any]]) -> None: + assert list(ds.iter_multi_items(value)) == expect diff --git a/tests/test_debug.py b/tests/test_debug.py index cf171d1..f51779c 100644 --- a/tests/test_debug.py +++ b/tests/test_debug.py @@ -245,7 +245,6 @@ def test_get_machine_id(): assert isinstance(rv, bytes) -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.parametrize("crash", (True, False)) @pytest.mark.dev_server def test_basic(dev_server, crash): diff --git a/tests/test_exceptions.py b/tests/test_exceptions.py index ad20b3f..67d76d2 100644 --- a/tests/test_exceptions.py +++ b/tests/test_exceptions.py @@ -37,6 +37,7 @@ def test_proxy_exception(): (exceptions.RequestEntityTooLarge, 413), (exceptions.RequestURITooLarge, 414), (exceptions.UnsupportedMediaType, 415), + (exceptions.MisdirectedRequest, 421), (exceptions.UnprocessableEntity, 422), (exceptions.Locked, 423), (exceptions.InternalServerError, 500), diff --git a/tests/test_formparser.py b/tests/test_formparser.py index 1ecb012..ebd7fdd 100644 --- a/tests/test_formparser.py +++ b/tests/test_formparser.py @@ -122,13 +122,21 @@ def test_limiting(self): req.max_form_parts = 1 pytest.raises(RequestEntityTooLarge, lambda: req.form["foo"]) - def test_x_www_urlencoded_max_form_parts(self): + def test_urlencoded_no_max(self) -> None: r = Request.from_values(method="POST", data={"a": 1, "b": 2}) r.max_form_parts = 1 assert r.form["a"] == "1" assert r.form["b"] == "2" + def test_urlencoded_silent_decode(self) -> None: + r = Request.from_values( + data=b"\x80", + content_type="application/x-www-form-urlencoded", + method="POST", + ) + assert not r.form + def test_missing_multipart_boundary(self): data = ( b"--foo\r\nContent-Disposition: form-field; name=foo\r\n\r\n" @@ -448,3 +456,15 @@ def test_file_rfc2231_filename_continuations(self): ) as request: assert request.files["rfc2231"].filename == "a b c d e f.txt" assert request.files["rfc2231"].read() == b"file contents" + + +def test_multipart_max_form_memory_size() -> None: + """max_form_memory_size is tracked across multiple data events.""" + data = b"--bound\r\nContent-Disposition: form-field; name=a\r\n\r\n" + data += b"a" * 15 + b"\r\n--bound--" + # The buffer size is less than the max size, so multiple data events will be + # returned. The field size is greater than the max. + parser = formparser.MultiPartParser(max_form_memory_size=10, buffer_size=5) + + with pytest.raises(RequestEntityTooLarge): + parser.parse(io.BytesIO(data), b"bound", None) diff --git a/tests/test_http.py b/tests/test_http.py index bbd51ba..726b40b 100644 --- a/tests/test_http.py +++ b/tests/test_http.py @@ -107,14 +107,21 @@ def test_set_header(self): def test_list_header(self, value, expect): assert http.parse_list_header(value) == expect - def test_dict_header(self): - d = http.parse_dict_header('foo="bar baz", blah=42') - assert d == {"foo": "bar baz", "blah": "42"} + @pytest.mark.parametrize( + ("value", "expect"), + [ + ('foo="bar baz", blah=42', {"foo": "bar baz", "blah": "42"}), + ("foo, bar=", {"foo": None, "bar": ""}), + ("=foo, =", {}), + ], + ) + def test_dict_header(self, value, expect): + assert http.parse_dict_header(value) == expect def test_cache_control_header(self): cc = http.parse_cache_control_header("max-age=0, no-cache") assert cc.max_age == 0 - assert cc.no_cache + assert cc.no_cache is True cc = http.parse_cache_control_header( 'private, community="UCI"', None, datastructures.ResponseCacheControl ) @@ -125,17 +132,17 @@ def test_cache_control_header(self): assert c.no_cache is None assert c.private is None c.no_cache = True - assert c.no_cache == "*" + assert c.no_cache and c.no_cache is True c.private = True - assert c.private == "*" + assert c.private and c.private is True del c.private - assert c.private is None + assert not c.private and c.private is None # max_age is an int, other types are converted c.max_age = 3.1 - assert c.max_age == 3 + assert c.max_age == 3 and c["max-age"] == "3" del c.max_age c.s_maxage = 3.1 - assert c.s_maxage == 3 + assert c.s_maxage == 3 and c["s-maxage"] == "3" del c.s_maxage assert c.to_header() == "no-cache" @@ -204,6 +211,10 @@ def test_authorization_header(self): assert Authorization.from_header(None) is None assert Authorization.from_header("foo").type == "foo" + def test_authorization_ignore_invalid_parameters(self): + a = Authorization.from_header("Digest foo, bar=, =qux, =") + assert a.to_header() == 'Digest foo, bar=""' + def test_authorization_token_padding(self): # padded with = token = base64.b64encode(b"This has base64 padding").decode() @@ -361,8 +372,8 @@ def test_parse_options_header_empty(self, value, expect): ('v;a="b\\"c";d=e', {"a": 'b"c', "d": "e"}), # HTTP headers use \\ for internal \ ('v;a="c:\\\\"', {"a": "c:\\"}), - # Invalid trailing slash in quoted part is left as-is. - ('v;a="c:\\"', {"a": "c:\\"}), + # Part with invalid trailing slash is discarded. + ('v;a="c:\\"', {}), ('v;a="b\\\\\\"c"', {"a": 'b\\"c'}), # multipart form data uses %22 for internal " ('v;a="b%22c"', {"a": 'b"c'}), @@ -377,6 +388,8 @@ def test_parse_options_header_empty(self, value, expect): ("v;a*0=b;a*1=c;d=e", {"a": "bc", "d": "e"}), ("v;a*0*=b", {"a": "b"}), ("v;a*0*=UTF-8''b;a*1=c;a*2*=%C2%B5", {"a": "bcµ"}), + # Long invalid quoted string with trailing slashes does not freeze. + ('v;a="' + "\\" * 400, {}), ], ) def test_parse_options_header(self, value, expect) -> None: @@ -576,6 +589,14 @@ def test_cookie_samesite_invalid(self): with pytest.raises(ValueError): http.dump_cookie("foo", "bar", samesite="invalid") + def test_cookie_partitioned(self): + value = http.dump_cookie("foo", "bar", partitioned=True, secure=True) + assert value == "foo=bar; Secure; Path=/; Partitioned" + + def test_cookie_partitioned_sets_secure(self): + value = http.dump_cookie("foo", "bar", partitioned=True, secure=False) + assert value == "foo=bar; Secure; Path=/; Partitioned" + class TestRange: def test_if_range_parsing(self): diff --git a/tests/test_security.py b/tests/test_security.py index 6fad089..4559368 100644 --- a/tests/test_security.py +++ b/tests/test_security.py @@ -1,5 +1,4 @@ import os -import posixpath import sys import pytest @@ -26,7 +25,7 @@ def test_scrypt(): def test_pbkdf2(): value = generate_password_hash("secret", method="pbkdf2") assert check_password_hash(value, "secret") - assert value.startswith("pbkdf2:sha256:600000$") + assert value.startswith("pbkdf2:sha256:1000000$") def test_salted_hashes(): @@ -47,11 +46,17 @@ def test_invalid_method(): generate_password_hash("secret", "sha256") -def test_safe_join(): - assert safe_join("foo", "bar/baz") == posixpath.join("foo", "bar/baz") - assert safe_join("foo", "../bar/baz") is None - if os.name == "nt": - assert safe_join("foo", "foo\\bar") is None +@pytest.mark.parametrize( + ("path", "expect"), + [ + ("b/c", "a/b/c"), + ("../b/c", None), + ("b\\c", None if os.name == "nt" else "a/b\\c"), + ("//b/c", None), + ], +) +def test_safe_join(path, expect): + assert safe_join("a", path) == expect def test_safe_join_os_sep(): diff --git a/tests/test_serving.py b/tests/test_serving.py index 4abc755..6dd9d9d 100644 --- a/tests/test_serving.py +++ b/tests/test_serving.py @@ -1,3 +1,6 @@ +from __future__ import annotations + +import collections.abc as cabc import http.client import json import os @@ -5,11 +8,14 @@ import socket import ssl import sys +import typing as t from io import BytesIO from pathlib import Path +from unittest.mock import Mock from unittest.mock import patch import pytest +from watchdog import version as watchdog_version from watchdog.events import EVENT_TYPE_MODIFIED from watchdog.events import EVENT_TYPE_OPENED from watchdog.events import FileModifiedEvent @@ -23,8 +29,11 @@ from werkzeug.serving import make_ssl_devcert from werkzeug.test import stream_encode_multipart +if t.TYPE_CHECKING: + from conftest import DevServerClient + from conftest import StartDevServer + -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.parametrize( "kwargs", [ @@ -41,7 +50,9 @@ ], ) @pytest.mark.dev_server -def test_server(tmp_path, dev_server, kwargs: dict): +def test_server( + tmp_path: Path, dev_server: StartDevServer, kwargs: dict[str, t.Any] +) -> None: if kwargs.get("hostname") == "unix": kwargs["hostname"] = f"unix://{tmp_path / 'test.sock'}" @@ -51,9 +62,8 @@ def test_server(tmp_path, dev_server, kwargs: dict): assert r.json["PATH_INFO"] == "/" -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_untrusted_host(standard_app): +def test_untrusted_host(standard_app: DevServerClient) -> None: r = standard_app.request( "http://missing.test:1337/index.html#ignore", headers={"x-base-url": standard_app.url}, @@ -65,45 +75,42 @@ def test_untrusted_host(standard_app): assert r.json["SERVER_PORT"] == port -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_double_slash_path(standard_app): +def test_double_slash_path(standard_app: DevServerClient) -> None: r = standard_app.request("//double-slash") assert "double-slash" not in r.json["HTTP_HOST"] assert r.json["PATH_INFO"] == "/double-slash" -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_500_error(standard_app): +def test_500_error(standard_app: DevServerClient) -> None: r = standard_app.request("/crash") assert r.status == 500 assert b"Internal Server Error" in r.data -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_ssl_dev_cert(tmp_path, dev_server): - client = dev_server(ssl_context=make_ssl_devcert(tmp_path)) +def test_ssl_dev_cert(tmp_path: Path, dev_server: StartDevServer) -> None: + client = dev_server(ssl_context=make_ssl_devcert(os.fspath(tmp_path))) r = client.request() assert r.json["wsgi.url_scheme"] == "https" -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_ssl_object(dev_server): +def test_ssl_object(dev_server: StartDevServer) -> None: client = dev_server(ssl_context="custom") r = client.request() assert r.json["wsgi.url_scheme"] == "https" -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.parametrize("reloader_type", ["stat", "watchdog"]) @pytest.mark.skipif( os.name == "nt" and "CI" in os.environ, reason="unreliable on Windows during CI" ) @pytest.mark.dev_server -def test_reloader_sys_path(tmp_path, dev_server, reloader_type): +def test_reloader_sys_path( + tmp_path: Path, dev_server: StartDevServer, reloader_type: str +) -> None: """This tests the general behavior of the reloader. It also tests that fixing an import error triggers a reload, not just Python retrying the failed import. @@ -115,29 +122,51 @@ def test_reloader_sys_path(tmp_path, dev_server, reloader_type): assert client.request().status == 500 shutil.copyfile(Path(__file__).parent / "live_apps" / "standard_app.py", real_path) - client.wait_for_log(f" * Detected change in {str(real_path)!r}, reloading") + client.wait_for_log(f"Detected change in {str(real_path)!r}") client.wait_for_reload() assert client.request().status == 200 @patch.object(WatchdogReloaderLoop, "trigger_reload") -def test_watchdog_reloader_ignores_opened(mock_trigger_reload): +def test_watchdog_reloader_ignores_opened(mock_trigger_reload: Mock) -> None: reloader = WatchdogReloaderLoop() modified_event = FileModifiedEvent("") modified_event.event_type = EVENT_TYPE_MODIFIED reloader.event_handler.on_any_event(modified_event) mock_trigger_reload.assert_called_once() - reloader.trigger_reload.reset_mock() - + mock_trigger_reload.reset_mock() opened_event = FileModifiedEvent("") opened_event.event_type = EVENT_TYPE_OPENED reloader.event_handler.on_any_event(opened_event) - reloader.trigger_reload.assert_not_called() + mock_trigger_reload.assert_not_called() + + +@pytest.mark.skipif( + watchdog_version.VERSION_MAJOR < 5, + reason="'closed no write' event introduced in watchdog 5.0", +) +@patch.object(WatchdogReloaderLoop, "trigger_reload") +def test_watchdog_reloader_ignores_closed_no_write(mock_trigger_reload: Mock) -> None: + from watchdog.events import EVENT_TYPE_CLOSED_NO_WRITE # type: ignore[attr-defined] + + reloader = WatchdogReloaderLoop() + modified_event = FileModifiedEvent("") + modified_event.event_type = EVENT_TYPE_MODIFIED + reloader.event_handler.on_any_event(modified_event) + mock_trigger_reload.assert_called_once() + + mock_trigger_reload.reset_mock() + opened_event = FileModifiedEvent("") + opened_event.event_type = EVENT_TYPE_CLOSED_NO_WRITE + reloader.event_handler.on_any_event(opened_event) + mock_trigger_reload.assert_not_called() @pytest.mark.skipif(sys.version_info >= (3, 10), reason="not needed on >= 3.10") -def test_windows_get_args_for_reloading(monkeypatch, tmp_path): +def test_windows_get_args_for_reloading( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: argv = [str(tmp_path / "test.exe"), "run"] monkeypatch.setattr("sys.executable", str(tmp_path / "python.exe")) monkeypatch.setattr("sys.argv", argv) @@ -147,9 +176,10 @@ def test_windows_get_args_for_reloading(monkeypatch, tmp_path): assert rv == argv -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.parametrize("find", [_find_stat_paths, _find_watchdog_paths]) -def test_exclude_patterns(find): +def test_exclude_patterns( + find: t.Callable[[set[str], set[str]], cabc.Iterable[str]], +) -> None: # Select a path to exclude from the unfiltered list, assert that it is present and # then gets excluded. paths = find(set(), set()) @@ -161,9 +191,8 @@ def test_exclude_patterns(find): assert not any(p.startswith(path_to_exclude) for p in paths) -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_wrong_protocol(standard_app): +def test_wrong_protocol(standard_app: DevServerClient) -> None: """An HTTPS request to an HTTP server doesn't show a traceback. https://github.com/pallets/werkzeug/pull/838 """ @@ -172,12 +201,11 @@ def test_wrong_protocol(standard_app): with pytest.raises(ssl.SSLError): conn.request("GET", f"https://{standard_app.addr}") - assert "Traceback" not in standard_app.log.read() + assert "Traceback" not in standard_app.read_log() -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_content_type_and_length(standard_app): +def test_content_type_and_length(standard_app: DevServerClient) -> None: r = standard_app.request() assert "CONTENT_TYPE" not in r.json assert "CONTENT_LENGTH" not in r.json @@ -187,15 +215,16 @@ def test_content_type_and_length(standard_app): assert r.json["CONTENT_LENGTH"] == "2" -def test_port_is_int(): +def test_port_is_int() -> None: with pytest.raises(TypeError, match="port must be an integer"): - run_simple("127.0.0.1", "5000", None) + run_simple("127.0.0.1", "5000", None) # type: ignore[arg-type] -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.parametrize("send_length", [False, True]) @pytest.mark.dev_server -def test_chunked_request(monkeypatch, dev_server, send_length): +def test_chunked_request( + monkeypatch: pytest.MonkeyPatch, dev_server: StartDevServer, send_length: bool +) -> None: stream, length, boundary = stream_encode_multipart( { "value": "this is text", @@ -235,9 +264,8 @@ def test_chunked_request(monkeypatch, dev_server, send_length): assert environ["wsgi.input_terminated"] -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_multiple_headers_concatenated(standard_app): +def test_multiple_headers_concatenated(standard_app: DevServerClient) -> None: """A header key can be sent multiple times. The server will join all the values with commas. @@ -260,9 +288,8 @@ def test_multiple_headers_concatenated(standard_app): assert data["HTTP_XYZ"] == "a ,b,c ,d" -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_multiline_header_folding(standard_app): +def test_multiline_header_folding(standard_app: DevServerClient) -> None: """A header value can be split over multiple lines with a leading tab. The server will remove the newlines and preserve the tabs. @@ -280,9 +307,8 @@ def test_multiline_header_folding(standard_app): @pytest.mark.parametrize("endpoint", ["", "crash"]) -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_streaming_close_response(dev_server, endpoint): +def test_streaming_close_response(dev_server: StartDevServer, endpoint: str) -> None: """When using HTTP/1.0, chunked encoding is not supported. Fall back to Connection: close, but this allows no reliable way to distinguish between complete and truncated responses. @@ -292,9 +318,8 @@ def test_streaming_close_response(dev_server, endpoint): assert r.data == "".join(str(x) + "\n" for x in range(5)).encode() -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_streaming_chunked_response(dev_server): +def test_streaming_chunked_response(dev_server: StartDevServer) -> None: """When using HTTP/1.1, use Transfer-Encoding: chunked for streamed responses, since it can distinguish the end of the response without closing the connection. @@ -306,11 +331,20 @@ def test_streaming_chunked_response(dev_server): assert r.data == "".join(str(x) + "\n" for x in range(5)).encode() -@pytest.mark.filterwarnings("ignore::pytest.PytestUnraisableExceptionWarning") @pytest.mark.dev_server -def test_streaming_chunked_truncation(dev_server): +def test_streaming_chunked_truncation(dev_server: StartDevServer) -> None: """When using HTTP/1.1, chunked encoding allows the client to detect content truncated by a prematurely closed connection. """ with pytest.raises(http.client.IncompleteRead): dev_server("streaming", threaded=True).request("/crash") + + +@pytest.mark.dev_server +def test_host_with_ipv6_scope(dev_server: StartDevServer) -> None: + client = dev_server(override_client_addr="fe80::1ff:fe23:4567:890a%eth2") + r = client.request("/crash") + + assert r.status == 500 + assert b"Internal Server Error" in r.data + assert "Logging error" not in client.read_log() diff --git a/tests/test_wrappers.py b/tests/test_wrappers.py index f756944..8bc063c 100644 --- a/tests/test_wrappers.py +++ b/tests/test_wrappers.py @@ -16,11 +16,11 @@ from werkzeug.datastructures import Headers from werkzeug.datastructures import ImmutableList from werkzeug.datastructures import ImmutableMultiDict -from werkzeug.datastructures import ImmutableOrderedMultiDict from werkzeug.datastructures import LanguageAccept from werkzeug.datastructures import MIMEAccept from werkzeug.datastructures import MultiDict from werkzeug.datastructures import WWWAuthenticate +from werkzeug.datastructures.structures import _ImmutableOrderedMultiDict from werkzeug.exceptions import BadRequest from werkzeug.exceptions import RequestedRangeNotSatisfiable from werkzeug.exceptions import SecurityError @@ -998,9 +998,10 @@ def generate_items(): assert resp.response == ["foo", "bar", "baz"] +@pytest.mark.filterwarnings("ignore:'OrderedMultiDict':DeprecationWarning") def test_form_data_ordering(): class MyRequest(wrappers.Request): - parameter_storage_class = ImmutableOrderedMultiDict + parameter_storage_class = _ImmutableOrderedMultiDict req = MyRequest.from_values("/?foo=1&bar=0&foo=3") assert list(req.args) == ["foo", "bar"] @@ -1009,7 +1010,7 @@ class MyRequest(wrappers.Request): ("bar", "0"), ("foo", "3"), ] - assert isinstance(req.args, ImmutableOrderedMultiDict) + assert isinstance(req.args, _ImmutableOrderedMultiDict) assert isinstance(req.values, CombinedMultiDict) assert req.values["foo"] == "1" assert req.values.getlist("foo") == ["1", "3"] diff --git a/tox.ini b/tox.ini index f7bc0b3..cebd251 100644 --- a/tox.ini +++ b/tox.ini @@ -1,6 +1,6 @@ [tox] envlist = - py3{12,11,10,9,8} + py3{13,12,11,10,9} pypy310 style typing @@ -28,16 +28,25 @@ commands = mypy deps = -r requirements/docs.txt commands = sphinx-build -E -W -b dirhtml docs docs/_build/dirhtml +[testenv:update-actions] +labels = update +deps = gha-update +commands = gha-update + +[testenv:update-pre_commit] +labels = update +deps = pre-commit +skip_install = true +commands = pre-commit autoupdate -j4 + [testenv:update-requirements] -deps = - pip-tools - pre-commit +labels = update +deps = pip-tools skip_install = true change_dir = requirements commands = - pre-commit autoupdate -j4 - pip-compile -U build.in - pip-compile -U docs.in - pip-compile -U tests.in - pip-compile -U typing.in - pip-compile -U dev.in + pip-compile build.in -q {posargs:-U} + pip-compile docs.in -q {posargs:-U} + pip-compile tests.in -q {posargs:-U} + pip-compile typing.in -q {posargs:-U} + pip-compile dev.in -q {posargs:-U}