diff options
| author | David Lord <davidism@gmail.com> | 2021-01-15 07:25:49 -0800 |
|---|---|---|
| committer | David Lord <davidism@gmail.com> | 2021-01-15 07:47:13 -0800 |
| commit | 9a1a877d54bb56775881eb75a63b5b881ef6e770 (patch) | |
| tree | 5da1c6bbf97728d50557f170f2fdb4c5ad1d4349 | |
| parent | 8606f8616e7d96211d3dfac54b6ccfa8da75613d (diff) | |
| download | werkzeug-unsplit-wrappers.tar.gz | |
merge request and response wrapper mixinsunsplit-wrappers
32 files changed, 2730 insertions, 2828 deletions
diff --git a/docs/quickstart.rst b/docs/quickstart.rst index 6a1712da..abe5c798 100644 --- a/docs/quickstart.rst +++ b/docs/quickstart.rst @@ -65,7 +65,7 @@ This way we can also access URL arguments (the query string) and data that was transmitted in a POST/PUT request. For testing purposes we can create a request object from supplied data -using the :meth:`~BaseRequest.from_values` method: +using the :meth:`~Request.from_values` method: >>> from io import StringIO >>> data = "name=this+is+encoded+form+data&another_key=another+one" @@ -102,7 +102,7 @@ example:: The files are represented as :class:`FileStorage` objects which provide some common operations to work with them. -Request headers can be accessed by using the :class:`~BaseRequest.headers` +Request headers can be accessed by using the :class:`~Request.headers` attribute: >>> request.headers['Content-Length'] @@ -245,7 +245,7 @@ code or provide a message as well: '400 BAD REQUEST' As you can see attributes work in both directions. So you can set both -:attr:`~BaseResponse.status` and :attr:`~BaseResponse.status_code` and the +:attr:`~Response.status` and :attr:`~Response.status_code` and the change will be reflected to the other. Also common headers are exposed as attributes or with methods to set / @@ -307,7 +307,7 @@ response conditional against a request. Which means that if the request can assure that it has the information already, no data besides the headers is sent over the network which saves traffic. For that you should set at least an etag (which is used for comparison) and the date header and then -call :class:`~BaseRequest.make_conditional` with the request object. +call :class:`~Request.make_conditional` with the request object. The response is modified accordingly (status code changed, response body removed, entity headers removed etc.) diff --git a/docs/request_data.rst b/docs/request_data.rst index db338d11..83c62780 100644 --- a/docs/request_data.rst +++ b/docs/request_data.rst @@ -18,7 +18,7 @@ The input stream has no end-of-file marker. If you would call the application to hang on conforming servers. This is actually intentional however painful. Werkzeug solves that problem by wrapping the input stream in a special :class:`LimitedStream`. The input stream is exposed -on the request objects as :attr:`~BaseRequest.stream`. This one is either +on the request objects as :attr:`~Request.stream`. This one is either an empty stream (if the form data was parsed) or a limited stream with the contents of the input stream. @@ -28,8 +28,8 @@ When does Werkzeug Parse? Werkzeug parses the incoming data under the following situations: -- you access either :attr:`~BaseRequest.form`, :attr:`~BaseRequest.files`, - or :attr:`~BaseRequest.stream` and the request method was +- you access either :attr:`~Request.form`, :attr:`~Request.files`, + or :attr:`~Request.stream` and the request method was `POST` or `PUT`. - if you call :func:`parse_form_data`. @@ -52,31 +52,31 @@ How does it Parse? The standard Werkzeug parsing behavior handles three cases: - input content type was `multipart/form-data`. In this situation the - :class:`~BaseRequest.stream` will be empty and - :class:`~BaseRequest.form` will contain the regular `POST` / `PUT` - data, :class:`~BaseRequest.files` will contain the uploaded + :class:`~Request.stream` will be empty and + :class:`~Request.form` will contain the regular `POST` / `PUT` + data, :class:`~Request.files` will contain the uploaded files as :class:`FileStorage` objects. - input content type was `application/x-www-form-urlencoded`. Then the - :class:`~BaseRequest.stream` will be empty and - :class:`~BaseRequest.form` will contain the regular `POST` / `PUT` - data and :class:`~BaseRequest.files` will be empty. -- the input content type was neither of them, :class:`~BaseRequest.stream` + :class:`~Request.stream` will be empty and + :class:`~Request.form` will contain the regular `POST` / `PUT` + data and :class:`~Request.files` will be empty. +- the input content type was neither of them, :class:`~Request.stream` points to a :class:`LimitedStream` with the input data for further processing. -Special note on the :attr:`~BaseRequest.get_data` method: Calling this +Special note on the :attr:`~Request.get_data` method: Calling this loads the full request data into memory. This is only safe to do if the -:attr:`~BaseRequest.max_content_length` is set. Also you can *either* -read the stream *or* call :meth:`~BaseRequest.get_data`. +:attr:`~Request.max_content_length` is set. Also you can *either* +read the stream *or* call :meth:`~Request.get_data`. Limiting Request Data --------------------- To avoid being the victim of a DDOS attack you can set the maximum -accepted content length and request field sizes. The :class:`BaseRequest` -class has two attributes for that: :attr:`~BaseRequest.max_content_length` -and :attr:`~BaseRequest.max_form_memory_size`. +accepted content length and request field sizes. The :class:`Request` +class has two attributes for that: :attr:`~Request.max_content_length` +and :attr:`~Request.max_form_memory_size`. The first one can be used to limit the total content length. For example by setting it to ``1024 * 1024 * 16`` the request won't accept more than @@ -84,7 +84,7 @@ by setting it to ``1024 * 1024 * 16`` the request won't accept more than Because certain data can't be moved to the hard disk (regular post data) whereas temporary files can, there is a second limit you can set. The -:attr:`~BaseRequest.max_form_memory_size` limits the size of `POST` +:attr:`~Request.max_form_memory_size` limits the size of `POST` transmitted form data. By setting it to ``1024 * 1024 * 2`` you can make sure that all in memory-stored fields are not more than 2MB in size. @@ -96,25 +96,5 @@ How to extend Parsing? ---------------------- Modern web applications transmit a lot more than multipart form data or -url encoded data. To extend the capabilities, subclass :class:`BaseRequest` +url encoded data. To extend the capabilities, subclass :class:`Request` or :class:`Request` and add or extend methods. - -There is already a mixin that provides JSON parsing:: - - from werkzeug.wrappers import Request - from werkzeug.wrappers.json import JSONMixin - - class JSONRequest(JSONMixin, Request): - pass - -The basic implementation of that looks like:: - - import json - from werkzeug.utils import cached_property - from werkzeug.wrappers import Request - - class JSONRequest(Request): - @cached_property - def json(self): - if self.mimetype == "application/json": - return json.loads(self.data) diff --git a/docs/terms.rst b/docs/terms.rst index a582b665..088aaa45 100644 --- a/docs/terms.rst +++ b/docs/terms.rst @@ -23,7 +23,7 @@ application but does not do any request processing. Usually you have a view function or controller method that processes the request and assembles a response object. -A response object is *not* necessarily the :class:`BaseResponse` object or a +A response object is *not* necessarily the :class:`Response` class or a subclass thereof. For example Pylons/webob provide a very similar response class that can diff --git a/docs/unicode.rst b/docs/unicode.rst index 1731c8fe..abeff138 100644 --- a/docs/unicode.rst +++ b/docs/unicode.rst @@ -60,14 +60,14 @@ encoding and error handling. .. code-block:: python - from werkzeug.wrappers import Request as _Request - from werkzeug.wrappers import Response as _Response + from werkzeug.wrappers.request import Request + from werkzeug.wrappers.response import Response - class Request(_Request): + class Latin1Request(Request): charset = "latin1" encoding_errors = "strict" - class Response(_BaseResponse): + class Latin1Response(Response): charset = "latin1" The error handling can only be changed for the request. Werkzeug will diff --git a/docs/wrappers.rst b/docs/wrappers.rst index dbad941b..b6a0e47e 100644 --- a/docs/wrappers.rst +++ b/docs/wrappers.rst @@ -73,152 +73,20 @@ For the response object the following rules apply: 4. It's possible to create copies using `copy.deepcopy`. -Base Wrappers -============= - -These objects implement a common set of operations. They are missing fancy -addon functionality like user agent parsing or etag handling. These features -are available by mixing in various mixin classes or using :class:`Request` and -:class:`Response`. - -.. autoclass:: BaseRequest - :members: - - .. attribute:: environ - - The WSGI environment that the request object uses for data retrival. - - .. attribute:: shallow - - `True` if this request object is shallow (does not modify :attr:`environ`), - `False` otherwise. - - .. automethod:: _get_file_stream - - -.. autoclass:: BaseResponse - :members: - - .. attribute:: response - - The application iterator. If constructed from a string this will be a - list, otherwise the object provided as application iterator. (The first - argument passed to :class:`BaseResponse`) - - .. attribute:: headers - - A :class:`Headers` object representing the response headers. - - .. attribute:: direct_passthrough - - If ``direct_passthrough=True`` was passed to the response object or if - this attribute was set to `True` before using the response object as - WSGI application, the wrapped iterator is returned unchanged. This - makes it possible to pass a special `wsgi.file_wrapper` to the response - object. See :func:`wrap_file` for more details. - - .. automethod:: __call__ - - .. automethod:: _ensure_sequence - - -Mixin Classes -============= - -Werkzeug also provides helper mixins for various HTTP related functionality -such as etags, cache control, user agents etc. When subclassing you can -mix those classes in to extend the functionality of the :class:`BaseRequest` -or :class:`BaseResponse` object. Here a small example for a request object -that parses accept headers:: - - from werkzeug.wrappers import AcceptMixin, BaseRequest - - class Request(BaseRequest, AcceptMixin): - pass - -The :class:`Request` and :class:`Response` classes subclass the :class:`BaseRequest` -and :class:`BaseResponse` classes and implement all the mixins Werkzeug provides: - +Wrapper Classes +=============== .. autoclass:: Request - -.. autoclass:: Response - - -Common Descriptors ------------------- - -.. autoclass:: CommonRequestDescriptorsMixin - :members: - -.. autoclass:: CommonResponseDescriptorsMixin - :members: - - -Response Stream ---------------- - -.. autoclass:: ResponseStreamMixin - :members: - - -Accept ------- - -.. autoclass:: AcceptMixin - :members: - - -Authentication --------------- - -.. autoclass:: AuthorizationMixin - :members: - -.. autoclass:: WWWAuthenticateMixin - :members: - - -CORS ----- - -.. autoclass:: werkzeug.wrappers.cors.CORSRequestMixin :members: + :member-order: bysource -.. autoclass:: werkzeug.wrappers.cors.CORSResponseMixin - :members: - - -ETag ----- - -.. autoclass:: ETagRequestMixin - :members: - -.. autoclass:: ETagResponseMixin - :members: - - -User Agent ----------- + .. automethod:: _get_file_stream -.. autoclass:: UserAgentMixin - :members: - - -Extra Mixin Classes -=================== - -These mixins are not included in the default :class:`Request` and -:class:`Response` classes. They provide extra behavior that needs to be -opted into by creating your own subclasses:: - - class Response(JSONMixin, BaseResponse): - pass +.. autoclass:: Response + :members: + :member-order: bysource -JSON ----- + .. automethod:: __call__ -.. autoclass:: werkzeug.wrappers.json.JSONMixin - :members: + .. automethod:: _ensure_sequence diff --git a/examples/coolmagic/utils.py b/examples/coolmagic/utils.py index f96b2092..ae286c40 100644 --- a/examples/coolmagic/utils.py +++ b/examples/coolmagic/utils.py @@ -9,8 +9,8 @@ from jinja2 import Environment from jinja2 import FileSystemLoader from werkzeug.local import Local from werkzeug.local import LocalManager -from werkzeug.wrappers import BaseRequest -from werkzeug.wrappers import BaseResponse +from werkzeug.wrappers import Request as BaseRequest +from werkzeug.wrappers import Response as BaseResponse local = Local() @@ -62,7 +62,7 @@ class Request(BaseRequest): charset = "utf-8" def __init__(self, environ, url_adapter): - BaseRequest.__init__(self, environ) + super().__init__(environ) self.url_adapter = url_adapter local.request = self diff --git a/examples/i18nurls/application.py b/examples/i18nurls/application.py index 0d105778..f0c2ca94 100644 --- a/examples/i18nurls/application.py +++ b/examples/i18nurls/application.py @@ -5,8 +5,8 @@ from jinja2 import PackageLoader from werkzeug.exceptions import HTTPException from werkzeug.exceptions import NotFound from werkzeug.routing import RequestRedirect -from werkzeug.wrappers import BaseResponse -from werkzeug.wrappers import Request as _Request +from werkzeug.wrappers import Request as BaseRequest +from werkzeug.wrappers import Response as BaseResponse from .urls import map @@ -24,7 +24,7 @@ def expose(name): return wrapped -class Request(_Request): +class Request(BaseRequest): def __init__(self, environ, urls): super().__init__(environ) self.urls = urls diff --git a/examples/simplewiki/utils.py b/examples/simplewiki/utils.py index ced91c64..6cafab4a 100644 --- a/examples/simplewiki/utils.py +++ b/examples/simplewiki/utils.py @@ -8,8 +8,8 @@ from werkzeug.local import LocalManager from werkzeug.urls import url_encode from werkzeug.urls import url_quote from werkzeug.utils import cached_property -from werkzeug.wrappers import BaseRequest -from werkzeug.wrappers import BaseResponse +from werkzeug.wrappers import Request as BaseRequest +from werkzeug.wrappers import Response as BaseResponse # calculate the path to the templates an create the template loader @@ -93,7 +93,7 @@ class Response(BaseResponse): ): if isinstance(response, Stream): response = response.render("html", encoding=None, doctype="html") - BaseResponse.__init__(self, response, status, headers, mimetype, content_type) + super().__init__(response, status, headers, mimetype, content_type) class Pagination: diff --git a/examples/upload.py b/examples/upload.py index ac084250..4fa952de 100644 --- a/examples/upload.py +++ b/examples/upload.py @@ -1,21 +1,21 @@ """All uploaded files are directly send back to the client.""" from werkzeug.serving import run_simple -from werkzeug.wrappers import BaseRequest -from werkzeug.wrappers import BaseResponse +from werkzeug.wrappers import Request +from werkzeug.wrappers import Response from werkzeug.wsgi import wrap_file def view_file(req): if "uploaded_file" not in req.files: - return BaseResponse("no file uploaded") + return Response("no file uploaded") f = req.files["uploaded_file"] - return BaseResponse( + return Response( wrap_file(req.environ, f), mimetype=f.content_type, direct_passthrough=True ) def upload_file(req): - return BaseResponse( + return Response( """<h1>Upload File</h1> <form action="" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"> @@ -26,7 +26,7 @@ def upload_file(req): def application(environ, start_response): - req = BaseRequest(environ) + req = Request(environ) if req.method == "POST": resp = view_file(req) else: diff --git a/examples/webpylike/webpylike.py b/examples/webpylike/webpylike.py index 8b1c837a..e7a9cebb 100644 --- a/examples/webpylike/webpylike.py +++ b/examples/webpylike/webpylike.py @@ -8,16 +8,8 @@ from werkzeug.exceptions import HTTPException from werkzeug.exceptions import MethodNotAllowed from werkzeug.exceptions import NotFound from werkzeug.exceptions import NotImplemented -from werkzeug.wrappers import BaseRequest -from werkzeug.wrappers import BaseResponse - - -class Request(BaseRequest): - """Encapsulates a request.""" - - -class Response(BaseResponse): - """Encapsulates a response.""" +from werkzeug.wrappers import Request +from werkzeug.wrappers import Response # noqa: F401 class View: diff --git a/src/werkzeug/_internal.py b/src/werkzeug/_internal.py index 4b1523c1..513af334 100644 --- a/src/werkzeug/_internal.py +++ b/src/werkzeug/_internal.py @@ -15,7 +15,7 @@ from weakref import WeakKeyDictionary if t.TYPE_CHECKING: from wsgiref.types import WSGIApplication from wsgiref.types import WSGIEnvironment - from .wrappers.base_request import BaseRequest # noqa: F401 + from .wrappers.request import Request # noqa: F401 _logger: t.Optional[logging.Logger] = None _signature_cache = WeakKeyDictionary() # type: ignore @@ -156,7 +156,7 @@ def _wsgi_encoding_dance( return s.encode(charset).decode("latin1", errors) -def _get_environ(obj: t.Union["WSGIEnvironment", "BaseRequest"]) -> "WSGIEnvironment": +def _get_environ(obj: t.Union["WSGIEnvironment", "Request"]) -> "WSGIEnvironment": env = getattr(obj, "environ", obj) assert isinstance( env, dict diff --git a/src/werkzeug/debug/__init__.py b/src/werkzeug/debug/__init__.py index df090376..b7da854d 100644 --- a/src/werkzeug/debug/__init__.py +++ b/src/werkzeug/debug/__init__.py @@ -16,8 +16,8 @@ from os.path import join from .._internal import _log from ..http import parse_cookie from ..security import gen_salt -from ..wrappers import BaseRequest as Request -from ..wrappers import BaseResponse as Response +from ..wrappers.request import Request +from ..wrappers.response import Response from .console import Console from .tbtools import get_current_traceback from .tbtools import render_console_html diff --git a/src/werkzeug/exceptions.py b/src/werkzeug/exceptions.py index 43d3097b..6872e427 100644 --- a/src/werkzeug/exceptions.py +++ b/src/werkzeug/exceptions.py @@ -6,16 +6,14 @@ Usage Example .. code-block:: python - from werkzeug.wrappers import BaseRequest - from werkzeug.wsgi import responder + from werkzeug.wrappers.request import Request from werkzeug.exceptions import HTTPException, NotFound def view(request): raise NotFound() - @responder - def application(environ, start_response): - request = BaseRequest(environ) + @Request.application + def application(request): try: return view(request) except HTTPException as e: @@ -35,14 +33,13 @@ code, you can add a second except for a specific subclass of an error: .. code-block:: python - @responder - def application(environ, start_response): - request = BaseRequest(environ) + @Request.application + def application(request): try: return view(request) - except NotFound, e: + except NotFound as e: return not_found(request) - except HTTPException, e: + except HTTPException as e: return e """ import sys diff --git a/src/werkzeug/formparser.py b/src/werkzeug/formparser.py index 3b7e95e8..f5875d56 100644 --- a/src/werkzeug/formparser.py +++ b/src/werkzeug/formparser.py @@ -91,7 +91,7 @@ def parse_form_data( :param environ: the WSGI environment to be used for parsing. :param stream_factory: An optional callable that returns a new read and writeable file descriptor. This callable works - the same as :meth:`~BaseResponse._get_file_stream`. + the same as :meth:`Response._get_file_stream`. :param charset: The character set for URL and url encoded form data. :param errors: The encoding error behavior. :param max_form_memory_size: the maximum number of bytes to be accepted for @@ -151,7 +151,7 @@ class FormDataParser: :param stream_factory: An optional callable that returns a new read and writeable file descriptor. This callable works - the same as :meth:`~BaseResponse._get_file_stream`. + the same as :meth:`Response._get_file_stream`. :param charset: The character set for URL and url encoded form data. :param errors: The encoding error behavior. :param max_form_memory_size: the maximum number of bytes to be accepted for diff --git a/src/werkzeug/test.py b/src/werkzeug/test.py index 231b7843..a500034a 100644 --- a/src/werkzeug/test.py +++ b/src/werkzeug/test.py @@ -35,9 +35,6 @@ from .urls import url_parse from .urls import url_unparse from .urls import url_unquote from .utils import get_content_type -from .wrappers.base_request import BaseRequest -from .wrappers.base_response import BaseResponse -from .wrappers.json import JSONMixin from .wrappers.request import Request from .wrappers.response import Response from .wsgi import ClosingIterator @@ -245,7 +242,7 @@ class EnvironBuilder: or request objects from arbitrary data. The signature of this class is also used in some other places as of - Werkzeug 0.5 (:func:`create_environ`, :meth:`BaseResponse.from_values`, + Werkzeug 0.5 (:func:`create_environ`, :meth:`Response.from_values`, :meth:`Client.open`). Because of this most of the functionality is available through the constructor alone. @@ -829,17 +826,6 @@ class ClientRedirectError(Exception): class Client: """This class allows you to send requests to a wrapped application. - The response wrapper can be a class or factory function that takes - three arguments: app_iter, status and headers. The default response - wrapper just returns a tuple. - - Example:: - - class ClientResponse(BaseResponse): - ... - - client = Client(MyApplication(), response_wrapper=ClientResponse) - The use_cookies parameter indicates whether cookies should be stored and sent for subsequent requests. This is True by default, but passing False will disable this behaviour. @@ -865,7 +851,7 @@ class Client: ) -> None: self.application = application - if response_wrapper in {None, BaseResponse, Response}: + if response_wrapper in {None, Response}: response_wrapper = TestResponse elif not isinstance(response_wrapper, TestResponse): response_wrapper = type( @@ -1060,8 +1046,8 @@ class Client: request = arg.get_request() elif isinstance(arg, dict): request = EnvironBuilder.from_environ(arg).get_request() - elif isinstance(arg, BaseRequest): - request = t.cast(Request, arg) + elif isinstance(arg, Request): + request = arg if request is None: builder = EnvironBuilder(*args, **kwargs) @@ -1255,7 +1241,7 @@ def run_wsgi_app( return app_iter, status, Headers(headers) -class TestResponse(JSONMixin, Response): # type: ignore +class TestResponse(Response): """:class:`~werkzeug.wrappers.Response` subclass that provides extra information about requests made with the test :class:`Client`. diff --git a/src/werkzeug/testapp.py b/src/werkzeug/testapp.py index 480fcd0c..0f93da58 100644 --- a/src/werkzeug/testapp.py +++ b/src/werkzeug/testapp.py @@ -9,8 +9,8 @@ from html import escape from textwrap import wrap from . import __version__ as _werkzeug_version -from .wrappers import BaseRequest as Request -from .wrappers import BaseResponse as Response +from .wrappers.request import Request +from .wrappers.response import Response if t.TYPE_CHECKING: from wsgiref.types import StartResponse diff --git a/src/werkzeug/wrappers/accept.py b/src/werkzeug/wrappers/accept.py index d1c3c563..20ae656b 100644 --- a/src/werkzeug/wrappers/accept.py +++ b/src/werkzeug/wrappers/accept.py @@ -1,50 +1,13 @@ -from ..datastructures import Accept -from ..datastructures import CharsetAccept -from ..datastructures import EnvironHeaders -from ..datastructures import LanguageAccept -from ..datastructures import MIMEAccept -from ..http import parse_accept_header -from ..utils import cached_property +import warnings class AcceptMixin: - """A mixin for classes with an :attr:`~BaseResponse.environ` attribute - to get all the HTTP accept headers as - :class:`~werkzeug.datastructures.Accept` objects (or subclasses - thereof). - """ - - headers: EnvironHeaders - - @cached_property - def accept_mimetypes(self) -> MIMEAccept: - """List of mimetypes this client supports as - :class:`~werkzeug.datastructures.MIMEAccept` object. - """ - return parse_accept_header(self.headers.get("Accept"), MIMEAccept) - - @cached_property - def accept_charsets(self) -> CharsetAccept: - """List of charsets this client supports as - :class:`~werkzeug.datastructures.CharsetAccept` object. - """ - return parse_accept_header(self.headers.get("Accept-Charset"), CharsetAccept) - - @cached_property - def accept_encodings(self) -> Accept: - """List of encodings this client accepts. Encodings in a HTTP term - are compression encodings such as gzip. For charsets have a look at - :attr:`accept_charset`. - """ - return parse_accept_header(self.headers.get("Accept-Encoding")) - - @cached_property - def accept_languages(self) -> LanguageAccept: - """List of languages this client accepts as - :class:`~werkzeug.datastructures.LanguageAccept` object. - - .. versionchanged 0.5 - In previous versions this was a regular - :class:`~werkzeug.datastructures.Accept` object. - """ - return parse_accept_header(self.headers.get("Accept-Language"), LanguageAccept) + def __init__(self, *args, **kwargs): + warnings.warn( + "'AcceptMixin' is deprecated and will be removed in" + " Werkzeug version 2.1. 'Request' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wrappers/auth.py b/src/werkzeug/wrappers/auth.py index 6db7a741..a5ea216c 100644 --- a/src/werkzeug/wrappers/auth.py +++ b/src/werkzeug/wrappers/auth.py @@ -1,42 +1,25 @@ -import typing as t - -from ..datastructures import Authorization -from ..datastructures import EnvironHeaders -from ..datastructures import Headers -from ..datastructures import WWWAuthenticate -from ..http import parse_authorization_header -from ..http import parse_www_authenticate_header -from ..utils import cached_property +import warnings class AuthorizationMixin: - """Adds an :attr:`authorization` property that represents the parsed - value of the `Authorization` header as - :class:`~werkzeug.datastructures.Authorization` object. - """ - - headers: EnvironHeaders - - @cached_property - def authorization(self) -> t.Optional[Authorization]: - """The `Authorization` object in parsed form.""" - return parse_authorization_header(self.headers.get("Authorization")) + def __init__(self, *args, **kwargs): + warnings.warn( + "'AuthorizationMixin' is deprecated and will be removed in" + " Werkzeug version 2.1. 'Request' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) class WWWAuthenticateMixin: - """Adds a :attr:`www_authenticate` property to a response object.""" - - headers: Headers - - @property - def www_authenticate(self) -> WWWAuthenticate: - """The `WWW-Authenticate` header in a parsed form.""" - - def on_update(www_auth: WWWAuthenticate) -> None: - if not www_auth and "www-authenticate" in self.headers: - del self.headers["www-authenticate"] - elif www_auth: - self.headers["WWW-Authenticate"] = www_auth.to_header() - - header = self.headers.get("www-authenticate") - return parse_www_authenticate_header(header, on_update) + def __init__(self, *args, **kwargs): + warnings.warn( + "'WWWAuthenticateMixin' is deprecated and will be removed" + " in Werkzeug version 2.1. 'Response' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wrappers/base_request.py b/src/werkzeug/wrappers/base_request.py index 6cb3334a..970eb2ce 100644 --- a/src/werkzeug/wrappers/base_request.py +++ b/src/werkzeug/wrappers/base_request.py @@ -1,688 +1,37 @@ -import typing as t -from functools import update_wrapper -from io import BytesIO +import warnings -from .._internal import _to_str -from .._internal import _wsgi_decoding_dance -from ..datastructures import CombinedMultiDict -from ..datastructures import EnvironHeaders -from ..datastructures import FileStorage -from ..datastructures import ImmutableList -from ..datastructures import ImmutableMultiDict -from ..datastructures import iter_multi_items -from ..datastructures import MultiDict -from ..formparser import default_stream_factory -from ..formparser import FormDataParser -from ..http import parse_cookie -from ..http import parse_list_header -from ..http import parse_options_header -from ..urls import url_decode -from ..utils import cached_property -from ..utils import environ_property -from ..wsgi import get_content_length -from ..wsgi import get_current_url -from ..wsgi import get_host -from ..wsgi import get_input_stream +from .request import Request -if t.TYPE_CHECKING: - from wsgiref.types import WSGIApplication - from wsgiref.types import WSGIEnvironment - -class BaseRequest: - """Very basic request object. This does not implement advanced stuff like - entity tag parsing or cache controls. The request object is created with - the WSGI environment as first argument and will add itself to the WSGI - environment as ``'werkzeug.request'`` unless it's created with - `populate_request` set to False. - - There are a couple of mixins available that add additional functionality - to the request object, there is also a class called `Request` which - subclasses `BaseRequest` and all the important mixins. - - It's a good idea to create a custom subclass of the :class:`BaseRequest` - and add missing functionality either via mixins or direct implementation. - Here an example for such subclasses:: - - from werkzeug.wrappers import BaseRequest, ETagRequestMixin - - class Request(BaseRequest, ETagRequestMixin): - pass - - Request objects are **read only**. As of 0.5 modifications are not - allowed in any place. Unlike the lower level parsing functions the - request object will use immutable objects everywhere possible. - - Per default the request object will assume all the text data is `utf-8` - encoded. Please refer to :doc:`/unicode` for more details about - customizing the behavior. - - Per default the request object will be added to the WSGI - environment as `werkzeug.request` to support the debugging system. - If you don't want that, set `populate_request` to `False`. - - If `shallow` is `True` the environment is initialized as shallow - object around the environ. Every operation that would modify the - environ in any way (such as consuming form data) raises an exception - unless the `shallow` attribute is explicitly set to `False`. This - is useful for middlewares where you don't want to consume the form - data by accident. A shallow request is not populated to the WSGI - environment. - - .. versionchanged:: 0.5 - read-only mode was enforced by using immutables classes for all - data. - """ - - #: the charset for the request, defaults to utf-8 - charset: str = "utf-8" - - #: the error handling procedure for errors, defaults to 'replace' - encoding_errors: str = "replace" - - #: the maximum content length. This is forwarded to the form data - #: parsing function (:func:`parse_form_data`). When set and the - #: :attr:`form` or :attr:`files` attribute is accessed and the - #: parsing fails because more than the specified value is transmitted - #: a :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised. - #: - #: Have a look at :doc:`/request_data` for more details. - #: - #: .. versionadded:: 0.5 - max_content_length: t.Optional[int] = None - - #: the maximum form field size. This is forwarded to the form data - #: parsing function (:func:`parse_form_data`). When set and the - #: :attr:`form` or :attr:`files` attribute is accessed and the - #: data in memory for post data is longer than the specified value a - #: :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised. - #: - #: Have a look at :doc:`/request_data` for more details. - #: - #: .. versionadded:: 0.5 - max_form_memory_size: t.Optional[int] = None - - #: 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 - #: possible to use mutable structures, but this is not recommended. - #: - #: .. versionadded:: 0.6 - parameter_storage_class: t.Type[MultiDict] = ImmutableMultiDict - - #: the type to be used for list values from the incoming WSGI environment. - #: By default an :class:`~werkzeug.datastructures.ImmutableList` is used - #: (for example for :attr:`access_list`). - #: - #: .. versionadded:: 0.6 - list_storage_class: t.Type[t.List] = ImmutableList - - #: The type to be used for dict values from the incoming WSGI - #: environment. (For example for :attr:`cookies`.) By default an - #: :class:`~werkzeug.datastructures.ImmutableMultiDict` is used. - #: - #: .. versionchanged:: 1.0.0 - #: Changed to ``ImmutableMultiDict`` to support multiple values. - #: - #: .. versionadded:: 0.6 - dict_storage_class: t.Type[MultiDict] = ImmutableMultiDict - - #: The form data parser that shoud be used. Can be replaced to customize - #: the form date parsing. - form_data_parser_class: t.Type[FormDataParser] = FormDataParser - - #: Optionally a list of hosts that is trusted by this request. By default - #: all hosts are trusted which means that whatever the client sends the - #: host is will be accepted. - #: - #: Because `Host` and `X-Forwarded-Host` headers can be set to any value by - #: a malicious client, it is recommended to either set this property or - #: implement similar validation in the proxy (if application is being run - #: behind one). - #: - #: .. versionadded:: 0.9 - trusted_hosts: t.Optional[t.List[str]] = None - - #: Indicates whether the data descriptor should be allowed to read and - #: buffer up the input stream. By default it's enabled. - #: - #: .. versionadded:: 0.9 - disable_data_descriptor: bool = False - - def __init__( - self, - environ: "WSGIEnvironment", - populate_request: bool = True, - shallow: bool = False, - ) -> None: - self.environ = environ - if populate_request and not shallow: - self.environ["werkzeug.request"] = self - self.shallow = shallow - - def __repr__(self) -> str: - # make sure the __repr__ even works if the request was created - # from an invalid WSGI environment. If we display the request - # in a debug session we don't want the repr to blow up. - args = [] - try: - args.append(f"'{self.url}'") - args.append(f"[{self.method}]") - except Exception: - args.append("(invalid WSGI environ)") - - return f"<{type(self).__name__} {' '.join(args)}>" - - @property - def url_charset(self) -> str: - """The charset that is assumed for URLs. Defaults to the value - of :attr:`charset`. - - .. versionadded:: 0.6 - """ - return self.charset - - @classmethod - def from_values(cls, *args, **kwargs) -> "BaseRequest": - """Create a new request object based on the values provided. If - environ is given missing values are filled from there. This method is - useful for small scripts when you need to simulate a request from an URL. - Do not use this method for unittesting, there is a full featured client - object (:class:`Client`) that allows to create multipart requests, - support for cookies etc. - - This accepts the same options as the - :class:`~werkzeug.test.EnvironBuilder`. - - .. versionchanged:: 0.5 - This method now accepts the same arguments as - :class:`~werkzeug.test.EnvironBuilder`. Because of this the - `environ` parameter is now called `environ_overrides`. - - :return: request object - """ - from ..test import EnvironBuilder - - charset = kwargs.pop("charset", cls.charset) - kwargs["charset"] = charset - builder = EnvironBuilder(*args, **kwargs) - try: - return builder.get_request(cls) # type: ignore - finally: - builder.close() - - @classmethod - def application( - cls, f: t.Callable[["BaseRequest"], "WSGIApplication"] - ) -> "WSGIApplication": - """Decorate a function as responder that accepts the request as - the last argument. This works like the :func:`responder` - decorator but the function is passed the request object as the - last argument and the request object will be closed - automatically:: - - @Request.application - def my_wsgi_app(request): - return Response('Hello World!') - - As of Werkzeug 0.14 HTTP exceptions are automatically caught and - converted to responses instead of failing. - - :param f: the WSGI callable to decorate - :return: a new WSGI callable - """ - #: return a callable that wraps the -2nd argument with the request - #: and calls the function with all the arguments up to that one and - #: the request. The return value is then called with the latest - #: two arguments. This makes it possible to use this decorator for - #: both standalone WSGI functions as well as bound methods and - #: partially applied functions. - from ..exceptions import HTTPException - - def application(*args): - request = cls(args[-2]) - with request: - try: - resp = f(*args[:-2] + (request,)) - except HTTPException as e: - resp = e.get_response(args[-2]) - return resp(*args[-2:]) - - return update_wrapper(application, f) - - def _get_file_stream( - self, - total_content_length: int, - content_type: t.Optional[str], - filename: t.Optional[str] = None, - content_length: t.Optional[int] = None, - ): - """Called to get a stream for the file upload. - - This must provide a file-like class with `read()`, `readline()` - and `seek()` methods that is both writeable and readable. - - The default implementation returns a temporary file if the total - content length is higher than 500KB. Because many browsers do not - provide a content length for the files only the total content - length matters. - - :param total_content_length: the total content length of all the - data in the request combined. This value - is guaranteed to be there. - :param content_type: the mimetype of the uploaded file. - :param filename: the filename of the uploaded file. May be `None`. - :param content_length: the length of this file. This value is usually - not provided because webbrowsers do not provide - this value. - """ - return default_stream_factory( - total_content_length=total_content_length, - filename=filename, - content_type=content_type, - content_length=content_length, +class _FakeSubclassCheck(type): + def __subclasscheck__(cls, subclass): + warnings.warn( + "'BaseRequest' is deprecated and will be removed in" + " Werkzeug version 2.1. Use 'issubclass(obj, Request)'" + " instead.", + DeprecationWarning, + stacklevel=2, ) + return issubclass(subclass, Request) - @property - def want_form_data_parsed(self) -> bool: - """Returns True if the request method carries content. As of - Werkzeug 0.9 this will be the case if a content type is transmitted. - - .. versionadded:: 0.8 - """ - return bool(self.environ.get("CONTENT_TYPE")) - - def make_form_data_parser(self) -> FormDataParser: - """Creates the form data parser. Instantiates the - :attr:`form_data_parser_class` with some parameters. - - .. versionadded:: 0.8 - """ - return self.form_data_parser_class( - self._get_file_stream, - self.charset, - self.encoding_errors, - self.max_form_memory_size, - self.max_content_length, - self.parameter_storage_class, + def __instancecheck__(cls, instance): + warnings.warn( + "'BaseRequest' is deprecated and will be removed in" + " Werkzeug version 2.1. Use 'isinstance(obj, Request)'" + " instead.", + DeprecationWarning, + stacklevel=2, ) - - def _load_form_data(self) -> None: - """Method used internally to retrieve submitted data. After calling - this sets `form` and `files` on the request object to multi dicts - filled with the incoming form data. As a matter of fact the input - stream will be empty afterwards. You can also call this method to - force the parsing of the form data. - - .. versionadded:: 0.8 - """ - # abort early if we have already consumed the stream - if "form" in self.__dict__: - return - - _assert_not_shallow(self) - - if self.want_form_data_parsed: - content_type = self.environ.get("CONTENT_TYPE", "") - content_length = get_content_length(self.environ) - mimetype, options = parse_options_header(content_type) - parser = self.make_form_data_parser() - data = parser.parse( - self._get_stream_for_parsing(), mimetype, content_length, options - ) - else: - data = ( - self.stream, - self.parameter_storage_class(), - self.parameter_storage_class(), - ) - - # inject the values into the instance dict so that we bypass - # our cached_property non-data descriptor. - d = self.__dict__ - d["stream"], d["form"], d["files"] = data - - def _get_stream_for_parsing(self) -> t.BinaryIO: - """This is the same as accessing :attr:`stream` with the difference - that if it finds cached data from calling :meth:`get_data` first it - will create a new stream out of the cached data. - - .. versionadded:: 0.9.3 - """ - cached_data = getattr(self, "_cached_data", None) - if cached_data is not None: - return BytesIO(cached_data) - return self.stream - - def close(self) -> None: - """Closes associated resources of this request object. This - closes all file handles explicitly. You can also use the request - object in a with statement which will automatically close it. - - .. versionadded:: 0.9 - """ - files = self.__dict__.get("files") - for _key, value in iter_multi_items(files or ()): - value.close() - - def __enter__(self) -> "BaseRequest": - return self - - def __exit__(self, exc_type, exc_value, tb) -> None: - self.close() - - @cached_property - def stream(self) -> t.BinaryIO: - """ - If the incoming form data was not encoded with a known mimetype - the data is stored unmodified in this stream for consumption. Most - of the time it is a better idea to use :attr:`data` which will give - you that data as a string. The stream only returns the data once. - - Unlike :attr:`input_stream` this stream is properly guarded that you - can't accidentally read past the length of the input. Werkzeug will - internally always refer to this stream to read data which makes it - possible to wrap this object with a stream that does filtering. - - .. versionchanged:: 0.9 - This stream is now always available but might be consumed by the - form parser later on. Previously the stream was only set if no - parsing happened. - """ - _assert_not_shallow(self) - return get_input_stream(self.environ) - - input_stream = environ_property( - "wsgi.input", - """The WSGI input stream. - - In general it's a bad idea to use this one because you can - easily read past the boundary. Use the :attr:`stream` - instead.""", - ) - - @cached_property - def args(self) -> "MultiDict[str, str]": - """The parsed URL parameters (the part in the URL after the question - mark). - - By default an - :class:`~werkzeug.datastructures.ImmutableMultiDict` - is returned from this function. This can be changed by setting - :attr:`parameter_storage_class` to a different type. This might - be necessary if the order of the form data is important. - """ - return url_decode( - self.environ.get("QUERY_STRING", "").encode("latin1"), - self.url_charset, - errors=self.encoding_errors, - cls=self.parameter_storage_class, - ) - - @cached_property - def data(self) -> bytes: - """ - Contains the incoming request data as string in case it came with - a mimetype Werkzeug does not handle. - """ - - if self.disable_data_descriptor: - raise AttributeError("data descriptor is disabled") - # XXX: this should eventually be deprecated. - - # We trigger form data parsing first which means that the descriptor - # will not cache the data that would otherwise be .form or .files - # data. This restores the behavior that was there in Werkzeug - # before 0.9. New code should use :meth:`get_data` explicitly as - # this will make behavior explicit. - return self.get_data(parse_form_data=True) - - def get_data( - self, cache: bool = True, as_text: bool = False, parse_form_data: bool = False - ) -> bytes: - """This reads the buffered incoming data from the client into one - bytes object. By default this is cached but that behavior can be - changed by setting `cache` to `False`. - - Usually it's a bad idea to call this method without checking the - content length first as a client could send dozens of megabytes or more - to cause memory problems on the server. - - Note that if the form data was already parsed this method will not - return anything as form data parsing does not cache the data like - this method does. To implicitly invoke form data parsing function - set `parse_form_data` to `True`. When this is done the return value - of this method will be an empty string if the form parser handles - the data. This generally is not necessary as if the whole data is - cached (which is the default) the form parser will used the cached - data to parse the form data. Please be generally aware of checking - the content length first in any case before calling this method - to avoid exhausting server memory. - - If `as_text` is set to `True` the return value will be a decoded - string. - - .. versionadded:: 0.9 - """ - rv = getattr(self, "_cached_data", None) - if rv is None: - if parse_form_data: - self._load_form_data() - rv = self.stream.read() - if cache: - self._cached_data = rv - if as_text: - rv = rv.decode(self.charset, self.encoding_errors) - return rv - - @cached_property - def form(self) -> "ImmutableMultiDict[str, str]": - """The form parameters. By default an - :class:`~werkzeug.datastructures.ImmutableMultiDict` - is returned from this function. This can be changed by setting - :attr:`parameter_storage_class` to a different type. This might - be necessary if the order of the form data is important. - - Please keep in mind that file uploads will not end up here, but instead - in the :attr:`files` attribute. - - .. versionchanged:: 0.9 - - Previous to Werkzeug 0.9 this would only contain form data for POST - and PUT requests. - """ - self._load_form_data() - return self.form - - @cached_property - def values(self) -> "CombinedMultiDict[str, str]": - """A :class:`werkzeug.datastructures.CombinedMultiDict` that combines - :attr:`args` and :attr:`form`.""" - args = [] - for d in self.args, self.form: - if not isinstance(d, MultiDict): - d = MultiDict(d) - args.append(d) - return CombinedMultiDict(args) - - @cached_property - def files(self) -> "ImmutableMultiDict[str, FileStorage]": - """:class:`~werkzeug.datastructures.MultiDict` object containing - all uploaded files. Each key in :attr:`files` is the name from the - ``<input type="file" name="">``. Each value in :attr:`files` is a - Werkzeug :class:`~werkzeug.datastructures.FileStorage` object. - - It basically behaves like a standard file object you know from Python, - with the difference that it also has a - :meth:`~werkzeug.datastructures.FileStorage.save` function that can - store the file on the filesystem. - - Note that :attr:`files` will only contain data if the request method was - POST, PUT or PATCH and the ``<form>`` that posted to the request had - ``enctype="multipart/form-data"``. It will be empty otherwise. - - See the :class:`~werkzeug.datastructures.MultiDict` / - :class:`~werkzeug.datastructures.FileStorage` documentation for - more details about the used data structure. - """ - self._load_form_data() - return self.files - - @cached_property - def cookies(self) -> "ImmutableMultiDict[str, str]": - """A :class:`dict` with the contents of all cookies transmitted with - the request.""" - return parse_cookie( # type: ignore - self.environ, - self.charset, - self.encoding_errors, - cls=self.dict_storage_class, - ) - - @cached_property - def headers(self) -> EnvironHeaders: - """The headers from the WSGI environ as immutable - :class:`~werkzeug.datastructures.EnvironHeaders`. - """ - return EnvironHeaders(self.environ) - - @cached_property - def path(self) -> str: - """Requested path. This works a bit like the regular path - info in the WSGI environment but will always include a leading slash, - even if the URL root is accessed. - """ - raw_path = _wsgi_decoding_dance( - self.environ.get("PATH_INFO") or "", self.charset, self.encoding_errors - ) - return "/" + raw_path.lstrip("/") - - @cached_property - def full_path(self) -> str: - """Requested path, including the query string.""" - return f"{self.path}?{_to_str(self.query_string, self.url_charset)}" - - @cached_property - def script_root(self) -> str: - """The root path of the script without the trailing slash.""" - raw_path = _wsgi_decoding_dance( - self.environ.get("SCRIPT_NAME") or "", self.charset, self.encoding_errors - ) - return raw_path.rstrip("/") - - @cached_property - def url(self) -> str: - """The reconstructed current URL as IRI. - See also: :attr:`trusted_hosts`. - """ - return get_current_url(self.environ, trusted_hosts=self.trusted_hosts) - - @cached_property - def base_url(self) -> str: - """Like :attr:`url` but without the querystring - See also: :attr:`trusted_hosts`. - """ - return get_current_url( - self.environ, strip_querystring=True, trusted_hosts=self.trusted_hosts - ) - - @cached_property - def url_root(self) -> str: - """The full URL root (with hostname), this is the application - root as IRI. - See also: :attr:`trusted_hosts`. - """ - return get_current_url(self.environ, True, trusted_hosts=self.trusted_hosts) - - @cached_property - def host_url(self) -> str: - """Just the host with scheme as IRI. - See also: :attr:`trusted_hosts`. - """ - return get_current_url( - self.environ, host_only=True, trusted_hosts=self.trusted_hosts - ) - - @cached_property - def host(self) -> str: - """Just the host including the port if available. - See also: :attr:`trusted_hosts`. - """ - return get_host(self.environ, trusted_hosts=self.trusted_hosts) - - query_string = environ_property[bytes]( - "QUERY_STRING", - b"", - load_func=lambda x: x.encode("latin1"), - doc="The URL parameters as raw bytes.", - ) - method = environ_property( - "REQUEST_METHOD", - "GET", - load_func=lambda x: x.upper(), - doc="The request method. (For example ``'GET'`` or ``'POST'``).", - ) - - @cached_property - def access_route(self) -> t.List[str]: - """If a forwarded header exists this is a list of all ip addresses - from the client ip to the last proxy server. - """ - if "HTTP_X_FORWARDED_FOR" in self.environ: - return self.list_storage_class( - parse_list_header(self.environ["HTTP_X_FORWARDED_FOR"]) - ) - elif "REMOTE_ADDR" in self.environ: - return self.list_storage_class([self.environ["REMOTE_ADDR"]]) - return self.list_storage_class() - - @property - def remote_addr(self) -> t.Optional[str]: - """The remote address of the client.""" - return self.environ.get("REMOTE_ADDR") - - remote_user = environ_property[str]( - "REMOTE_USER", - doc="""If the server supports user authentication, and the - script is protected, this attribute contains the username the - user has authenticated as.""", - ) - scheme = environ_property[str]( - "wsgi.url_scheme", - doc=""" - URL scheme (http or https). - - .. versionadded:: 0.7""", - ) - is_secure = property( - lambda self: self.environ["wsgi.url_scheme"] == "https", - doc="`True` if the request is secure.", - ) - is_multithread = environ_property[bool]( - "wsgi.multithread", - doc="""boolean that is `True` if the application is served by a - multithreaded WSGI server.""", - ) - is_multiprocess = environ_property[bool]( - "wsgi.multiprocess", - doc="""boolean that is `True` if the application is served by a - WSGI server that spawns multiple processes.""", - ) - is_run_once = environ_property[bool]( - "wsgi.run_once", - doc="""boolean that is `True` if the application will be - executed only once in a process lifetime. This is the case for - CGI for example, but it's not guaranteed that the execution only - happens one time.""", - ) + return isinstance(instance, Request) -def _assert_not_shallow(request: BaseRequest) -> None: - if request.shallow: - raise RuntimeError( - "A shallow request tried to consume form data. If you really" - " want to do that, set `shallow` to False." +class BaseRequest(Request, metaclass=_FakeSubclassCheck): + def __init__(self, *args, **kwargs): + warnings.warn( + "'BaseRequest' is deprecated and will be removed in" + " Werkzeug version 2.1. 'Request' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, ) + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wrappers/base_response.py b/src/werkzeug/wrappers/base_response.py index 4e13dbba..9caf0ef0 100644 --- a/src/werkzeug/wrappers/base_response.py +++ b/src/werkzeug/wrappers/base_response.py @@ -1,760 +1,37 @@ -import typing -import typing as t import warnings -from datetime import datetime -from datetime import timedelta -from .._internal import _to_bytes -from .._internal import _to_str -from ..datastructures import Headers -from ..http import dump_cookie -from ..http import HTTP_STATUS_CODES -from ..http import remove_entity_headers -from ..urls import iri_to_uri -from ..urls import url_join -from ..utils import get_content_type -from ..wsgi import ClosingIterator -from ..wsgi import get_current_url +from .response import Response -if t.TYPE_CHECKING: - from wsgiref.types import StartResponse - from wsgiref.types import WSGIApplication - from wsgiref.types import WSGIEnvironment - -def _warn_if_string(iterable: t.Iterable) -> None: - """Helper for the response objects to check if the iterable returned - to the WSGI server is not a string. - """ - if isinstance(iterable, str): +class _FakeSubclassCheck(type): + def __subclasscheck__(cls, subclass): warnings.warn( - "Response iterable was set to a string. This will appear to" - " work but means that the server will send the data to the" - " client one character at a time. This is almost never" - " intended behavior, use 'response.data' to assign strings" - " to the response object.", + "'BaseResponse' is deprecated and will be removed in" + " Werkzeug version 2.1. Use 'issubclass(obj, Response)'" + " instead.", + DeprecationWarning, stacklevel=2, ) + return issubclass(subclass, Response) - -def _iter_encoded( - iterable: t.Iterable[t.Union[str, bytes]], charset: str -) -> t.Iterator[bytes]: - for item in iterable: - if isinstance(item, str): - yield item.encode(charset) - else: - yield item - - -def _clean_accept_ranges(accept_ranges: t.Union[bool, str]) -> str: - if accept_ranges is True: - return "bytes" - elif accept_ranges is False: - return "none" - elif isinstance(accept_ranges, str): - return accept_ranges - raise ValueError("Invalid accept_ranges value") - - -class BaseResponse: - """Base response class. The most important fact about a response object - is that it's a regular WSGI application. It's initialized with a couple - of response parameters (headers, body, status code etc.) and will start a - valid WSGI response when called with the environ and start response - callable. - - Because it's a WSGI application itself processing usually ends before the - actual response is sent to the server. This helps debugging systems - because they can catch all the exceptions before responses are started. - - Here a small example WSGI application that takes advantage of the - response objects:: - - from werkzeug.wrappers import BaseResponse as Response - - def index(): - return Response('Index page') - - def application(environ, start_response): - path = environ.get('PATH_INFO') or '/' - if path == '/': - response = index() - else: - response = Response('Not Found', status=404) - return response(environ, start_response) - - Like :class:`BaseRequest` which object is lacking a lot of functionality - implemented in mixins. This gives you a better control about the actual - API of your response objects, so you can create subclasses and add custom - functionality. A full featured response object is available as - :class:`Response` which implements a couple of useful mixins. - - To enforce a new type of already existing responses you can use the - :meth:`force_type` method. This is useful if you're working with different - subclasses of response objects and you want to post process them with a - known interface. - - Per default the response object will assume all the text data is `utf-8` - encoded. Please refer to :doc:`/unicode` for more details about - customizing the behavior. - - Response can be any kind of iterable or string. If it's a string it's - considered being an iterable with one item which is the string passed. - Headers can be a list of tuples or a - :class:`~werkzeug.datastructures.Headers` object. - - Special note for `mimetype` and `content_type`: For most mime types - `mimetype` and `content_type` work the same, the difference affects - only 'text' mimetypes. If the mimetype passed with `mimetype` is a - mimetype starting with `text/`, the charset parameter of the response - object is appended to it. In contrast the `content_type` parameter is - always added as header unmodified. - - .. versionchanged:: 0.5 - the `direct_passthrough` parameter was added. - - :param response: a string or response iterable. - :param status: a string with a status or an integer with the status code. - :param headers: a list of headers or a - :class:`~werkzeug.datastructures.Headers` object. - :param mimetype: the mimetype for the response. See notice above. - :param content_type: the content type for the response. See notice above. - :param direct_passthrough: if set to `True` :meth:`iter_encoded` is not - called before iteration which makes it - possible to pass special iterators through - unchanged (see :func:`wrap_file` for more - details.) - """ - - #: the charset of the response. - charset: str = "utf-8" - - #: the default status if none is provided. - default_status: int = 200 - - #: the default mimetype if none is provided. - default_mimetype: str = "text/plain" - - #: if set to `False` accessing properties on the response object will - #: not try to consume the response iterator and convert it into a list. - #: - #: .. versionadded:: 0.6.2 - #: - #: That attribute was previously called `implicit_seqence_conversion`. - #: (Notice the typo). If you did use this feature, you have to adapt - #: your code to the name change. - implicit_sequence_conversion: bool = True - - #: Should this response object correct the location header to be RFC - #: conformant? This is true by default. - #: - #: .. versionadded:: 0.8 - autocorrect_location_header: bool = True - - #: Should this response object automatically set the content-length - #: header if possible? This is true by default. - #: - #: .. versionadded:: 0.8 - automatically_set_content_length: bool = True - - #: Warn if a cookie header exceeds this size. The default, 4093, should be - #: safely `supported by most browsers <cookie_>`_. A cookie larger than - #: this size will still be sent, but it may be ignored or handled - #: incorrectly by some browsers. Set to 0 to disable this check. - #: - #: .. versionadded:: 0.13 - #: - #: .. _`cookie`: http://browsercookielimits.squawky.net/ - max_cookie_size: int = 4093 - - def __init__( - self, - response: t.Optional[ - t.Union[t.Iterable[bytes], bytes, t.Iterable[str], str] - ] = None, - status: t.Optional[t.Union[int, str]] = None, - headers: t.Optional[ - t.Union[ - t.Mapping[str, t.Union[str, int, t.Iterable[t.Union[str, int]]]], - t.Iterable[t.Tuple[str, t.Union[str, int]]], - ] - ] = None, - mimetype: t.Optional[str] = None, - content_type: t.Optional[str] = None, - direct_passthrough: bool = False, - ) -> None: - if isinstance(headers, Headers): - self.headers = headers - elif not headers: - self.headers = Headers() - else: - self.headers = Headers(headers) - - if content_type is None: - if mimetype is None and "content-type" not in self.headers: - mimetype = self.default_mimetype - if mimetype is not None: - mimetype = get_content_type(mimetype, self.charset) - content_type = mimetype - if content_type is not None: - self.headers["Content-Type"] = content_type - if status is None: - status = self.default_status - self.status = status # type: ignore - - self.direct_passthrough = direct_passthrough - self._on_close: t.List[t.Callable[[], t.Any]] = [] - - # we set the response after the headers so that if a class changes - # the charset attribute, the data is set in the correct charset. - if response is None: - self.response: t.Union[t.Iterable[bytes], t.Iterable[str]] = [] - elif isinstance(response, (str, bytes, bytearray)): - self.set_data(response) - else: - self.response = response - - def call_on_close(self, func: t.Callable[[], t.Any]) -> t.Callable[[], t.Any]: - """Adds a function to the internal list of functions that should - be called as part of closing down the response. Since 0.7 this - function also returns the function that was passed so that this - can be used as a decorator. - - .. versionadded:: 0.6 - """ - self._on_close.append(func) - return func - - def __repr__(self) -> str: - if self.is_sequence: - body_info = f"{sum(map(len, self.iter_encoded()))} bytes" - else: - body_info = "streamed" if self.is_streamed else "likely-streamed" - return f"<{type(self).__name__} {body_info} [{self.status}]>" - - @classmethod - def force_type( - cls, response: "BaseResponse", environ: t.Optional["WSGIEnvironment"] = None - ) -> "BaseResponse": - """Enforce that the WSGI response is a response object of the current - type. Werkzeug will use the :class:`BaseResponse` internally in many - situations like the exceptions. If you call :meth:`get_response` on an - exception you will get back a regular :class:`BaseResponse` object, even - if you are using a custom subclass. - - This method can enforce a given response type, and it will also - convert arbitrary WSGI callables into response objects if an environ - is provided:: - - # convert a Werkzeug response object into an instance of the - # MyResponseClass subclass. - response = MyResponseClass.force_type(response) - - # convert any WSGI application into a response object - response = MyResponseClass.force_type(response, environ) - - This is especially useful if you want to post-process responses in - the main dispatcher and use functionality provided by your subclass. - - Keep in mind that this will modify response objects in place if - possible! - - :param response: a response object or wsgi application. - :param environ: a WSGI environment object. - :return: a response object. - """ - if not isinstance(response, BaseResponse): - if environ is None: - raise TypeError( - "cannot convert WSGI application into response" - " objects without an environ" - ) - - from ..test import run_wsgi_app - - response = BaseResponse(*run_wsgi_app(response, environ)) - - response.__class__ = cls - return response - - @classmethod - def from_app( - cls, app: "WSGIApplication", environ: "WSGIEnvironment", buffered: bool = False - ) -> "BaseResponse": - """Create a new response object from an application output. This - works best if you pass it an application that returns a generator all - the time. Sometimes applications may use the `write()` callable - returned by the `start_response` function. This tries to resolve such - edge cases automatically. But if you don't get the expected output - you should set `buffered` to `True` which enforces buffering. - - :param app: the WSGI application to execute. - :param environ: the WSGI environment to execute against. - :param buffered: set to `True` to enforce buffering. - :return: a response object. - """ - from ..test import run_wsgi_app - - return cls(*run_wsgi_app(app, environ, buffered)) - - @property - def status_code(self) -> int: - """The HTTP status code as a number.""" - return self._status_code - - @status_code.setter - def status_code(self, code: int) -> None: - self.status = code # type: ignore - - @property - def status(self) -> str: - """The HTTP status code as a string.""" - return self._status - - @status.setter - def status(self, value: t.Union[str, int]) -> None: - if not isinstance(value, (str, bytes, int)): - raise TypeError("Invalid status argument") - - self._status, self._status_code = self._clean_status(value) - - def _clean_status(self, value: t.Union[str, int]) -> t.Tuple[str, int]: - status = _to_str(value, self.charset) - split_status = status.split(None, 1) - - if len(split_status) == 0: - raise ValueError("Empty status argument") - - if len(split_status) > 1: - if split_status[0].isdigit(): - # code and message - return status, int(split_status[0]) - - # multi-word message - return f"0 {status}", 0 - - if split_status[0].isdigit(): - # code only - status_code = int(split_status[0]) - - try: - status = f"{status_code} {HTTP_STATUS_CODES[status_code].upper()}" - except KeyError: - status = f"{status_code} UNKNOWN" - - return status, status_code - - # one-word message - return f"0 {status}", 0 - - @typing.overload - def get_data(self, as_text: "t.Literal[False]" = False) -> str: - ... - - @typing.overload - def get_data(self, as_text: "t.Literal[True]") -> bytes: - ... - - def get_data(self, as_text=False): - """The string representation of the response body. Whenever you call - this property the response iterable is encoded and flattened. This - can lead to unwanted behavior if you stream big data. - - This behavior can be disabled by setting - :attr:`implicit_sequence_conversion` to `False`. - - If `as_text` is set to `True` the return value will be a decoded - string. - - .. versionadded:: 0.9 - """ - self._ensure_sequence() - rv = b"".join(self.iter_encoded()) - if as_text: - rv = rv.decode(self.charset) - return rv - - def set_data(self, value: t.Union[bytes, str]) -> None: - """Sets a new string as response. The value must be a string or - bytes. If a string is set it's encoded to the charset of the - response (utf-8 by default). - - .. versionadded:: 0.9 - """ - # if a string is set, it's encoded directly so that we - # can set the content length - if isinstance(value, str): - value = value.encode(self.charset) - else: - value = bytes(value) - self.response = [value] - if self.automatically_set_content_length: - self.headers["Content-Length"] = str(len(value)) - - data = property( - get_data, - set_data, - doc="A descriptor that calls :meth:`get_data` and :meth:`set_data`.", - ) - - def calculate_content_length(self) -> t.Optional[int]: - """Returns the content length if available or `None` otherwise.""" - try: - self._ensure_sequence() - except RuntimeError: - return None - return sum(len(x) for x in self.iter_encoded()) - - def _ensure_sequence(self, mutable: bool = False) -> None: - """This method can be called by methods that need a sequence. If - `mutable` is true, it will also ensure that the response sequence - is a standard Python list. - - .. versionadded:: 0.6 - """ - if self.is_sequence: - # if we need a mutable object, we ensure it's a list. - if mutable and not isinstance(self.response, list): - self.response = list(self.response) # type: ignore - return - if self.direct_passthrough: - raise RuntimeError( - "Attempted implicit sequence conversion but the" - " response object is in direct passthrough mode." - ) - if not self.implicit_sequence_conversion: - raise RuntimeError( - "The response object required the iterable to be a" - " sequence, but the implicit conversion was disabled." - " Call make_sequence() yourself." - ) - self.make_sequence() - - def make_sequence(self) -> None: - """Converts the response iterator in a list. By default this happens - automatically if required. If `implicit_sequence_conversion` is - disabled, this method is not automatically called and some properties - might raise exceptions. This also encodes all the items. - - .. versionadded:: 0.6 - """ - if not self.is_sequence: - # if we consume an iterable we have to ensure that the close - # method of the iterable is called if available when we tear - # down the response - close = getattr(self.response, "close", None) - self.response = list(self.iter_encoded()) - if close is not None: - self.call_on_close(close) - - def iter_encoded(self) -> t.Iterator[bytes]: - """Iter the response encoded with the encoding of the response. - If the response object is invoked as WSGI application the return - value of this method is used as application iterator unless - :attr:`direct_passthrough` was activated. - """ - if __debug__: - _warn_if_string(self.response) - # Encode in a separate function so that self.response is fetched - # early. This allows us to wrap the response with the return - # value from get_app_iter or iter_encoded. - return _iter_encoded(self.response, self.charset) - - def set_cookie( - self, - key: str, - value: str = "", - max_age: t.Optional[t.Union[timedelta, int]] = None, - expires: t.Optional[t.Union[str, datetime, int, float]] = None, - path: t.Optional[str] = "/", - domain: t.Optional[str] = None, - secure: bool = False, - httponly: bool = False, - samesite: t.Optional[str] = None, - ) -> None: - """Sets a cookie. - - A warning is raised if the size of the cookie header exceeds - :attr:`max_cookie_size`, but the header will still be set. - - :param key: the key (name) of the cookie to be set. - :param value: the value of the cookie. - :param max_age: should be a number of seconds, or `None` (default) if - the cookie should last only as long as the client's - browser session. - :param expires: should be a `datetime` object or UNIX timestamp. - :param path: limits the cookie to a given path, per default it will - span the whole domain. - :param domain: if you want to set a cross-domain cookie. For example, - ``domain=".example.com"`` will set a cookie that is - readable by the domain ``www.example.com``, - ``foo.example.com`` etc. Otherwise, a cookie will only - be readable by the domain that set it. - :param secure: If ``True``, the cookie will only be available - via HTTPS. - :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". - """ - self.headers.add( - "Set-Cookie", - dump_cookie( - key, - value=value, - max_age=max_age, - expires=expires, - path=path, - domain=domain, - secure=secure, - httponly=httponly, - charset=self.charset, - max_size=self.max_cookie_size, - samesite=samesite, - ), + def __instancecheck__(cls, instance): + warnings.warn( + "'BaseResponse' is deprecated and will be removed in" + " Werkzeug version 2.1. Use 'isinstance(obj, Response)'" + " instead.", + DeprecationWarning, + stacklevel=2, ) + return isinstance(instance, Response) - def delete_cookie( - self, - key: str, - path: str = "/", - domain: t.Optional[str] = None, - secure: bool = False, - httponly: bool = False, - samesite: t.Optional[str] = None, - ): - """Delete a cookie. Fails silently if key doesn't exist. - :param key: the key (name) of the cookie to be deleted. - :param path: if the cookie that should be deleted was limited to a - path, the path has to be defined here. - :param domain: if the cookie that should be deleted was limited to a - domain, that domain has to be defined here. - :param secure: If ``True``, the cookie will only be available - via HTTPS. - :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". - """ - self.set_cookie( - key, - expires=0, - max_age=0, - path=path, - domain=domain, - secure=secure, - httponly=httponly, - samesite=samesite, +class BaseResponse(Response, metaclass=_FakeSubclassCheck): + def __init__(self, *args, **kwargs): + warnings.warn( + "'BaseResponse' is deprecated and will be removed in" + " Werkzeug version 2.1. 'Response' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, ) - - @property - def is_streamed(self) -> bool: - """If the response is streamed (the response is not an iterable with - a length information) this property is `True`. In this case streamed - means that there is no information about the number of iterations. - This is usually `True` if a generator is passed to the response object. - - This is useful for checking before applying some sort of post - filtering that should not take place for streamed responses. - """ - try: - len(self.response) # type: ignore - except (TypeError, AttributeError): - return True - return False - - @property - def is_sequence(self) -> bool: - """If the iterator is buffered, this property will be `True`. A - response object will consider an iterator to be buffered if the - response attribute is a list or tuple. - - .. versionadded:: 0.6 - """ - return isinstance(self.response, (tuple, list)) - - def close(self) -> None: - """Close the wrapped response if possible. You can also use the object - in a with statement which will automatically close it. - - .. versionadded:: 0.9 - Can now be used in a with statement. - """ - if hasattr(self.response, "close"): - self.response.close() # type: ignore - for func in self._on_close: - func() - - def __enter__(self) -> "BaseResponse": - return self - - def __exit__(self, exc_type, exc_value, tb): - self.close() - - def freeze(self) -> None: - """Call this method if you want to make your response object ready for - being pickled. This buffers the generator if there is one. It will - also set the `Content-Length` header to the length of the body. - - .. versionchanged:: 0.6 - The `Content-Length` header is now set. - """ - # we explicitly set the length to a list of the *encoded* response - # iterator. Even if the implicit sequence conversion is disabled. - self.response = list(self.iter_encoded()) - self.headers["Content-Length"] = str(sum(map(len, self.response))) - - def get_wsgi_headers(self, environ: "WSGIEnvironment") -> Headers: - """This is automatically called right before the response is started - and returns headers modified for the given environment. It returns a - copy of the headers from the response with some modifications applied - if necessary. - - For example the location header (if present) is joined with the root - URL of the environment. Also the content length is automatically set - to zero here for certain status codes. - - .. versionchanged:: 0.6 - Previously that function was called `fix_headers` and modified - the response object in place. Also since 0.6, IRIs in location - and content-location headers are handled properly. - - Also starting with 0.6, Werkzeug will attempt to set the content - length if it is able to figure it out on its own. This is the - case if all the strings in the response iterable are already - encoded and the iterable is buffered. - - :param environ: the WSGI environment of the request. - :return: returns a new :class:`~werkzeug.datastructures.Headers` - object. - """ - headers = Headers(self.headers) - location: t.Optional[str] = None - content_location: t.Optional[str] = None - content_length: t.Optional[t.Union[str, int]] = None - status = self.status_code - - # iterate over the headers to find all values in one go. Because - # get_wsgi_headers is used each response that gives us a tiny - # speedup. - for key, value in headers: - ikey = key.lower() - if ikey == "location": - location = value - elif ikey == "content-location": - content_location = value - elif ikey == "content-length": - content_length = value - - # make sure the location header is an absolute URL - if location is not None: - old_location = location - if isinstance(location, str): - # Safe conversion is necessary here as we might redirect - # to a broken URI scheme (for instance itms-services). - location = iri_to_uri(location, safe_conversion=True) - - if self.autocorrect_location_header: - current_url = get_current_url(environ, strip_querystring=True) - if isinstance(current_url, str): - current_url = iri_to_uri(current_url) - location = url_join(current_url, location) - if location != old_location: - headers["Location"] = location # type: ignore - - # make sure the content location is a URL - if content_location is not None and isinstance(content_location, str): - headers["Content-Location"] = iri_to_uri(content_location) - - if 100 <= status < 200 or status == 204: - # Per section 3.3.2 of RFC 7230, "a server MUST NOT send a - # Content-Length header field in any response with a status - # code of 1xx (Informational) or 204 (No Content)." - headers.remove("Content-Length") - elif status == 304: - remove_entity_headers(headers) - - # if we can determine the content length automatically, we - # should try to do that. But only if this does not involve - # flattening the iterator or encoding of strings in the - # response. We however should not do that if we have a 304 - # response. - if ( - self.automatically_set_content_length - and self.is_sequence - and content_length is None - and status not in (204, 304) - and not (100 <= status < 200) - ): - try: - content_length = sum(len(_to_bytes(x, "ascii")) for x in self.response) - except UnicodeError: - # Something other than bytes, can't safely figure out - # the length of the response. - pass - else: - headers["Content-Length"] = str(content_length) - - return headers - - def get_app_iter(self, environ: "WSGIEnvironment") -> t.Iterable[bytes]: - """Returns the application iterator for the given environ. Depending - on the request method and the current status code the return value - might be an empty response rather than the one from the response. - - If the request method is `HEAD` or the status code is in a range - where the HTTP specification requires an empty response, an empty - iterable is returned. - - .. versionadded:: 0.6 - - :param environ: the WSGI environment of the request. - :return: a response iterable. - """ - status = self.status_code - if ( - environ["REQUEST_METHOD"] == "HEAD" - or 100 <= status < 200 - or status in (204, 304) - ): - iterable: t.Iterable[bytes] = () - elif self.direct_passthrough: - if __debug__: - _warn_if_string(self.response) - return self.response # type: ignore - else: - iterable = self.iter_encoded() - return ClosingIterator(iterable, self.close) - - def get_wsgi_response( - self, environ: "WSGIEnvironment" - ) -> t.Tuple[t.Iterable[bytes], str, t.List[t.Tuple[str, str]]]: - """Returns the final WSGI response as tuple. The first item in - the tuple is the application iterator, the second the status and - the third the list of headers. The response returned is created - specially for the given environment. For example if the request - method in the WSGI environment is ``'HEAD'`` the response will - be empty and only the headers and status code will be present. - - .. versionadded:: 0.6 - - :param environ: the WSGI environment of the request. - :return: an ``(app_iter, status, headers)`` tuple. - """ - headers = self.get_wsgi_headers(environ) - app_iter = self.get_app_iter(environ) - return app_iter, self.status, headers.to_wsgi_list() - - def __call__( - self, environ: "WSGIEnvironment", start_response: "StartResponse" - ) -> t.Iterable[bytes]: - """Process this response as WSGI application. - - :param environ: the WSGI environment. - :param start_response: the response callable provided by the WSGI - server. - :return: an application iterator - """ - app_iter, status, headers = self.get_wsgi_response(environ) - start_response(status, headers) - return app_iter + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wrappers/common_descriptors.py b/src/werkzeug/wrappers/common_descriptors.py index c8b57370..1f752149 100644 --- a/src/werkzeug/wrappers/common_descriptors.py +++ b/src/werkzeug/wrappers/common_descriptors.py @@ -1,360 +1,25 @@ -import typing as t -from datetime import datetime -from datetime import timedelta - -from ..datastructures import CallbackDict -from ..datastructures import EnvironHeaders -from ..datastructures import Headers -from ..datastructures import HeaderSet -from ..http import dump_age -from ..http import dump_csp_header -from ..http import dump_header -from ..http import dump_options_header -from ..http import http_date -from ..http import parse_age -from ..http import parse_csp_header -from ..http import parse_date -from ..http import parse_options_header -from ..http import parse_set_header -from ..utils import cached_property -from ..utils import get_content_type -from ..utils import header_property -from ..wsgi import get_content_length - -if t.TYPE_CHECKING: - from wsgiref.types import WSGIEnvironment +import warnings class CommonRequestDescriptorsMixin: - """A mixin for :class:`BaseRequest` subclasses. Request objects that - mix this class in will automatically get descriptors for a couple of - HTTP headers with automatic type conversion. - - .. versionadded:: 0.5 - """ - - headers: Headers - - content_type = header_property[str]( - "Content-Type", - doc="""The Content-Type entity-header field indicates the media - type of the entity-body sent to the recipient or, in the case of - the HEAD method, the media type that would have been sent had - the request been a GET.""", - read_only=True, - ) - - @cached_property - def content_length(self) -> t.Optional[int]: - """The Content-Length entity-header field indicates the size of the - entity-body in bytes or, in the case of the HEAD method, the size of - the entity-body that would have been sent had the request been a - GET. - """ - return get_content_length(self.headers) - - content_encoding = header_property[str]( - "Content-Encoding", - doc="""The Content-Encoding entity-header field is used as a - modifier to the media-type. When present, its value indicates - what additional content codings have been applied to the - entity-body, and thus what decoding mechanisms must be applied - in order to obtain the media-type referenced by the Content-Type - header field. - - .. versionadded:: 0.9""", - read_only=True, - ) - content_md5 = header_property[str]( - "Content-MD5", - doc="""The Content-MD5 entity-header field, as defined in - RFC 1864, is an MD5 digest of the entity-body for the purpose of - providing an end-to-end message integrity check (MIC) of the - entity-body. (Note: a MIC is good for detecting accidental - modification of the entity-body in transit, but is not proof - against malicious attacks.) - - .. versionadded:: 0.9""", - read_only=True, - ) - referrer = header_property[str]( - "Referer", - doc="""The Referer[sic] request-header field allows the client - to specify, for the server's benefit, the address (URI) of the - resource from which the Request-URI was obtained (the - "referrer", although the header field is misspelled).""", - read_only=True, - ) - date = header_property( - "Date", - None, - parse_date, - doc="""The Date general-header field represents the date and - time at which the message was originated, having the same - semantics as orig-date in RFC 822.""", - read_only=True, - ) - max_forwards = header_property( - "Max-Forwards", - None, - int, - doc="""The Max-Forwards request-header field provides a - mechanism with the TRACE and OPTIONS methods to limit the number - of proxies or gateways that can forward the request to the next - inbound server.""", - read_only=True, - ) - - def _parse_content_type(self) -> None: - if not hasattr(self, "_parsed_content_type"): - self._parsed_content_type = parse_options_header( - self.headers.get("Content-Type", "") - ) - - @property - 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 - ``'text/html'``. - """ - self._parse_content_type() - return self._parsed_content_type[0].lower() - - @property - def mimetype_params(self) -> t.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'}``. - """ - self._parse_content_type() - return self._parsed_content_type[1] - - @cached_property - def pragma(self) -> HeaderSet: - """The Pragma general-header field is used to include - implementation-specific directives that might apply to any recipient - along the request/response chain. All pragma directives specify - optional behavior from the viewpoint of the protocol; however, some - systems MAY require that behavior be consistent with the directives. - """ - return parse_set_header(self.headers.get("Pragma", "")) - - -def _set_property(name: str, doc: t.Optional[str] = None) -> property: - def fget(self): - def on_update(header_set): - if not header_set and name in self.headers: - del self.headers[name] - elif header_set: - self.headers[name] = header_set.to_header() - - return parse_set_header(self.headers.get(name), on_update) - - def fset(self, value): - if not value: - del self.headers[name] - elif isinstance(value, str): - self.headers[name] = value - else: - self.headers[name] = dump_header(value) - - return property(fget, fset, doc=doc) + def __init__(self, *args, **kwargs): + warnings.warn( + "'CommonRequestDescriptorsMixin' is deprecated and will be" + " removed in Werkzeug version 2.1. 'Request' now includes" + " the functionality directly.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) class CommonResponseDescriptorsMixin: - """A mixin for :class:`BaseResponse` subclasses. Response objects that - mix this class in will automatically get descriptors for a couple of - HTTP headers with automatic type conversion. - """ - - charset: str - environ: "WSGIEnvironment" - headers: EnvironHeaders - - @property - def mimetype(self) -> t.Optional[str]: - """The mimetype (content type without charset etc.)""" - ct = self.headers.get("content-type") - - if ct: - return ct.split(";")[0].strip() - else: - return None - - @mimetype.setter - def mimetype(self, value: str) -> None: - self.headers["Content-Type"] = get_content_type(value, self.charset) - - @property - def mimetype_params(self) -> t.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'}``. - - .. versionadded:: 0.5 - """ - - def on_update(d): - self.headers["Content-Type"] = dump_options_header(self.mimetype, d) - - d = parse_options_header(self.headers.get("content-type", ""))[1] - return CallbackDict(d, on_update) - - location = header_property[str]( - "Location", - doc="""The Location response-header field is used to redirect - the recipient to a location other than the Request-URI for - completion of the request or identification of a new - resource.""", - ) - age = header_property( - "Age", - None, - parse_age, - dump_age, # type: ignore - doc="""The Age response-header field conveys the sender's - estimate of the amount of time since the response (or its - revalidation) was generated at the origin server. - - Age values are non-negative decimal integers, representing time - in seconds.""", - ) - content_type = header_property[str]( - "Content-Type", - doc="""The Content-Type entity-header field indicates the media - type of the entity-body sent to the recipient or, in the case of - the HEAD method, the media type that would have been sent had - the request been a GET.""", - ) - content_length = header_property( - "Content-Length", - None, - int, - str, - doc="""The Content-Length entity-header field indicates the size - of the entity-body, in decimal number of OCTETs, sent to the - recipient or, in the case of the HEAD method, the size of the - entity-body that would have been sent had the request been a - GET.""", - ) - content_location = header_property[str]( - "Content-Location", - doc="""The Content-Location entity-header field MAY be used to - supply the resource location for the entity enclosed in the - message when that entity is accessible from a location separate - from the requested resource's URI.""", - ) - content_encoding = header_property[str]( - "Content-Encoding", - doc="""The Content-Encoding entity-header field is used as a - modifier to the media-type. When present, its value indicates - what additional content codings have been applied to the - entity-body, and thus what decoding mechanisms must be applied - in order to obtain the media-type referenced by the Content-Type - header field.""", - ) - content_md5 = header_property[str]( - "Content-MD5", - doc="""The Content-MD5 entity-header field, as defined in - RFC 1864, is an MD5 digest of the entity-body for the purpose of - providing an end-to-end message integrity check (MIC) of the - entity-body. (Note: a MIC is good for detecting accidental - modification of the entity-body in transit, but is not proof - against malicious attacks.)""", - ) - content_security_policy = header_property( - "Content-Security-Policy", - None, - parse_csp_header, # type: ignore - dump_csp_header, - doc="""The Content-Security-Policy header adds an additional layer of - security to help detect and mitigate certain types of attacks.""", - ) - content_security_policy_report_only = header_property( - "Content-Security-Policy-Report-Only", - None, - parse_csp_header, # type: ignore - dump_csp_header, - doc="""The Content-Security-Policy-Report-Only header adds a csp policy - that is not enforced but is reported thereby helping detect - certain types of attacks.""", - ) - date = header_property( - "Date", - None, - parse_date, - http_date, - doc="""The Date general-header field represents the date and - time at which the message was originated, having the same - semantics as orig-date in RFC 822.""", - ) - expires = header_property( - "Expires", - None, - parse_date, - http_date, - doc="""The Expires entity-header field gives the date/time after - which the response is considered stale. A stale cache entry may - not normally be returned by a cache.""", - ) - last_modified = header_property( - "Last-Modified", - None, - parse_date, - http_date, - doc="""The Last-Modified entity-header field indicates the date - and time at which the origin server believes the variant was - last modified.""", - ) - - @property - def retry_after(self) -> t.Optional[datetime]: - """The Retry-After response-header field can be used with a - 503 (Service Unavailable) response to indicate how long the - service is expected to be unavailable to the requesting client. - - Time in seconds until expiration or date. - """ - value = self.headers.get("retry-after") - if value is None: - return None - elif value.isdigit(): - return datetime.utcnow() + timedelta(seconds=int(value)) - return parse_date(value) - - @retry_after.setter - def retry_after(self, value: t.Optional[t.Union[datetime, int, str]]) -> None: - if value is None: - if "retry-after" in self.headers: - del self.headers["retry-after"] - return - elif isinstance(value, datetime): - value = http_date(value) - else: - value = str(value) - self.headers["Retry-After"] = value - - vary = _set_property( - "Vary", - doc="""The Vary field value indicates the set of request-header - fields that fully determines, while the response is fresh, - whether a cache is permitted to use the response to reply to a - subsequent request without revalidation.""", - ) - content_language = _set_property( - "Content-Language", - doc="""The Content-Language entity-header field describes the - natural language(s) of the intended audience for the enclosed - entity. Note that this might not be equivalent to all the - languages used within the entity-body.""", - ) - allow = _set_property( - "Allow", - doc="""The Allow entity-header field lists the set of methods - supported by the resource identified by the Request-URI. The - purpose of this field is strictly to inform the recipient of - valid methods associated with the resource. An Allow header - field MUST be present in a 405 (Method Not Allowed) - response.""", - ) + def __init__(self, *args, **kwargs): + warnings.warn( + "'CommonResponseDescriptorMixin' is deprecated and will be" + " removed in Werkzeug version 2.1. 'Response' now includes" + " the functionality directly.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wrappers/cors.py b/src/werkzeug/wrappers/cors.py index a8f68cdf..929f2071 100644 --- a/src/werkzeug/wrappers/cors.py +++ b/src/werkzeug/wrappers/cors.py @@ -1,107 +1,25 @@ -import typing as t - -from ..datastructures import Headers -from ..http import dump_header -from ..http import parse_set_header -from ..utils import header_property +import warnings class CORSRequestMixin: - """A mixin for :class:`~werkzeug.wrappers.BaseRequest` subclasses - that adds descriptors for Cross Origin Resource Sharing (CORS) - headers. - - .. versionadded:: 1.0 - """ - - origin = header_property[str]( - "Origin", - doc=( - "The host that the request originated from. Set" - " :attr:`~CORSResponseMixin.access_control_allow_origin` on" - " the response to indicate which origins are allowed." - ), - read_only=True, - ) - - access_control_request_headers = header_property( - "Access-Control-Request-Headers", - load_func=parse_set_header, - doc=( - "Sent with a preflight request to indicate which headers" - " will be sent with the cross origin request. Set" - " :attr:`~CORSResponseMixin.access_control_allow_headers`" - " on the response to indicate which headers are allowed." - ), - read_only=True, - ) - - access_control_request_method = header_property[str]( - "Access-Control-Request-Method", - doc=( - "Sent with a preflight request to indicate which method" - " will be used for the cross origin request. Set" - " :attr:`~CORSResponseMixin.access_control_allow_methods`" - " on the response to indicate which methods are allowed." - ), - read_only=True, - ) + def __init__(self, *args, **kwargs): + warnings.warn( + "'CORSRequestMixin' is deprecated and will be removed in" + " Werkzeug version 2.1. 'Request' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) class CORSResponseMixin: - """A mixin for :class:`~werkzeug.wrappers.BaseResponse` subclasses - that adds descriptors for Cross Origin Resource Sharing (CORS) - headers. - - .. versionadded:: 1.0 - """ - - headers: Headers - - @property - def access_control_allow_credentials(self) -> bool: - """Whether credentials can be shared by the browser to - JavaScript code. As part of the preflight request it indicates - whether credentials can be used on the cross origin request. - """ - return "Access-Control-Allow-Credentials" in self.headers - - @access_control_allow_credentials.setter - def access_control_allow_credentials(self, value: t.Optional[bool]) -> None: - if value is True: - self.headers["Access-Control-Allow-Credentials"] = "true" - else: - self.headers.pop("Access-Control-Allow-Credentials", None) - - access_control_allow_headers = header_property( - "Access-Control-Allow-Headers", - load_func=parse_set_header, - dump_func=dump_header, - doc="Which headers can be sent with the cross origin request.", - ) - - access_control_allow_methods = header_property( - "Access-Control-Allow-Methods", - load_func=parse_set_header, - dump_func=dump_header, - doc="Which methods can be used for the cross origin request.", - ) - - access_control_allow_origin = header_property[str]( - "Access-Control-Allow-Origin", - doc="The origin or '*' for any origin that may make cross origin requests.", - ) - - access_control_expose_headers = header_property( - "Access-Control-Expose-Headers", - load_func=parse_set_header, - dump_func=dump_header, - doc="Which headers can be shared by the browser to JavaScript code.", - ) - - access_control_max_age = header_property( - "Access-Control-Max-Age", - load_func=int, - dump_func=str, - doc="The maximum age in seconds the access control settings can be cached for.", - ) + def __init__(self, *args, **kwargs): + warnings.warn( + "'CORSResponseMixin' is deprecated and will be removed in" + " Werkzeug version 2.1. 'Response' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wrappers/etag.py b/src/werkzeug/wrappers/etag.py index f290e3dd..e96d07a7 100644 --- a/src/werkzeug/wrappers/etag.py +++ b/src/werkzeug/wrappers/etag.py @@ -1,328 +1,25 @@ -import typing as t -from datetime import datetime - -from .._internal import _get_environ -from ..datastructures import ContentRange -from ..datastructures import EnvironHeaders -from ..datastructures import ETags -from ..datastructures import Headers -from ..datastructures import IfRange -from ..datastructures import Range -from ..datastructures import RequestCacheControl -from ..datastructures import ResponseCacheControl -from ..http import generate_etag -from ..http import http_date -from ..http import is_resource_modified -from ..http import parse_cache_control_header -from ..http import parse_content_range_header -from ..http import parse_date -from ..http import parse_etags -from ..http import parse_if_range_header -from ..http import parse_range_header -from ..http import quote_etag -from ..http import unquote_etag -from ..utils import cached_property -from ..utils import header_property -from ..wrappers.base_response import _clean_accept_ranges -from ..wsgi import _RangeWrapper - -if t.TYPE_CHECKING: - from wsgiref.types import WSGIEnvironment +import warnings class ETagRequestMixin: - """Add entity tag and cache descriptors to a request object or object with - a WSGI environment available as :attr:`~BaseRequest.environ`. This not - only provides access to etags but also to the cache control header. - """ - - headers: "EnvironHeaders" - - @cached_property - def cache_control(self) -> RequestCacheControl: - """A :class:`~werkzeug.datastructures.RequestCacheControl` object - for the incoming cache control headers. - """ - cache_control = self.headers.get("Cache-Control") - return parse_cache_control_header(cache_control, None, RequestCacheControl) - - @cached_property - def if_match(self) -> ETags: - """An object containing all the etags in the `If-Match` header. - - :rtype: :class:`~werkzeug.datastructures.ETags` - """ - return parse_etags(self.headers.get("If-Match")) - - @cached_property - def if_none_match(self) -> ETags: - """An object containing all the etags in the `If-None-Match` header. - - :rtype: :class:`~werkzeug.datastructures.ETags` - """ - return parse_etags(self.headers.get("If-None-Match")) - - @cached_property - def if_modified_since(self) -> t.Optional[datetime]: - """The parsed `If-Modified-Since` header as datetime object.""" - return parse_date(self.headers.get("If-Modified-Since")) - - @cached_property - def if_unmodified_since(self) -> t.Optional[datetime]: - """The parsed `If-Unmodified-Since` header as datetime object.""" - return parse_date(self.headers.get("If-Unmodified-Since")) - - @cached_property - def if_range(self) -> IfRange: - """The parsed `If-Range` header. - - .. versionadded:: 0.7 - - :rtype: :class:`~werkzeug.datastructures.IfRange` - """ - return parse_if_range_header(self.headers.get("If-Range")) - - @cached_property - def range(self) -> t.Optional[Range]: - """The parsed `Range` header. - - .. versionadded:: 0.7 - - :rtype: :class:`~werkzeug.datastructures.Range` - """ - return parse_range_header(self.headers.get("Range")) + def __init__(self, *args, **kwargs): + warnings.warn( + "'ETagRequestMixin' is deprecated and will be removed in" + " Werkzeug version 2.1. 'Request' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) class ETagResponseMixin: - """Adds extra functionality to a response object for etag and cache - handling. This mixin requires an object with at least a `headers` - object that implements a dict like interface similar to - :class:`~werkzeug.datastructures.Headers`. - - If you want the :meth:`freeze` method to automatically add an etag, you - have to mixin this method before the response base class. The default - response class does not do that. - """ - - status_code: int - headers: Headers - response: t.Iterable[bytes] - - @property - def cache_control(self) -> "ResponseCacheControl": - """The Cache-Control general-header field is used to specify - directives that MUST be obeyed by all caching mechanisms along the - request/response chain. - """ - - def on_update(cache_control): - if not cache_control and "cache-control" in self.headers: - del self.headers["cache-control"] - elif cache_control: - self.headers["Cache-Control"] = cache_control.to_header() - - return parse_cache_control_header( - self.headers.get("cache-control"), on_update, ResponseCacheControl + def __init__(self, *args, **kwargs): + warnings.warn( + "'ETagResponseMixin' is deprecated and will be removed in" + " Werkzeug version 2.1. 'Response' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, ) - - def _wrap_response(self, start: int, length: int) -> None: - """Wrap existing Response in case of Range Request context.""" - if self.status_code == 206: - self.response = _RangeWrapper(self.response, start, length) - - def _is_range_request_processable(self, environ: "WSGIEnvironment") -> bool: - """Return ``True`` if `Range` header is present and if underlying - resource is considered unchanged when compared with `If-Range` header. - """ - return ( - "HTTP_IF_RANGE" not in environ - or not is_resource_modified( - environ, - self.headers.get("etag"), - None, - self.headers.get("last-modified"), - ignore_if_range=False, - ) - ) and "HTTP_RANGE" in environ - - def _process_range_request( - self, - environ: "WSGIEnvironment", - complete_length: t.Optional[int] = None, - accept_ranges: t.Optional[t.Union[bool, str]] = None, - ) -> bool: - """Handle Range Request related headers (RFC7233). If `Accept-Ranges` - header is valid, and Range Request is processable, we set the headers - as described by the RFC, and wrap the underlying response in a - RangeWrapper. - - Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise. - - :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable` - if `Range` header could not be parsed or satisfied. - """ - from ..exceptions import RequestedRangeNotSatisfiable - - if ( - accept_ranges is None - or complete_length is None - or not self._is_range_request_processable(environ) - ): - return False - - parsed_range = parse_range_header(environ.get("HTTP_RANGE")) - - if parsed_range is None: - raise RequestedRangeNotSatisfiable(complete_length) - - range_tuple = parsed_range.range_for_length(complete_length) - content_range_header = parsed_range.to_content_range_header(complete_length) - - if range_tuple is None or content_range_header is None: - raise RequestedRangeNotSatisfiable(complete_length) - - content_length = range_tuple[1] - range_tuple[0] - self.headers["Content-Length"] = content_length - self.headers["Accept-Ranges"] = accept_ranges - self.content_range = content_range_header # type: ignore - self.status_code = 206 - self._wrap_response(range_tuple[0], content_length) - return True - - def make_conditional( - self, - request_or_environ: "WSGIEnvironment", - accept_ranges: t.Union[bool, str] = False, - complete_length: t.Optional[int] = None, - ): - """Make the response conditional to the request. This method works - best if an etag was defined for the response already. The `add_etag` - method can be used to do that. If called without etag just the date - header is set. - - This does nothing if the request method in the request or environ is - anything but GET or HEAD. - - For optimal performance when handling range requests, it's recommended - that your response data object implements `seekable`, `seek` and `tell` - methods as described by :py:class:`io.IOBase`. Objects returned by - :meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods. - - It does not remove the body of the response because that's something - the :meth:`__call__` function does for us automatically. - - Returns self so that you can do ``return resp.make_conditional(req)`` - but modifies the object in-place. - - :param request_or_environ: a request object or WSGI environment to be - used to make the response conditional - against. - :param accept_ranges: This parameter dictates the value of - `Accept-Ranges` header. If ``False`` (default), - the header is not set. If ``True``, it will be set - to ``"bytes"``. If ``None``, it will be set to - ``"none"``. If it's a string, it will use this - value. - :param complete_length: Will be used only in valid Range Requests. - It will set `Content-Range` complete length - value and compute `Content-Length` real value. - This parameter is mandatory for successful - Range Requests completion. - :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable` - if `Range` header could not be parsed or satisfied. - """ - environ = _get_environ(request_or_environ) - if environ["REQUEST_METHOD"] in ("GET", "HEAD"): - # if the date is not in the headers, add it now. We however - # will not override an already existing header. Unfortunately - # this header will be overriden by many WSGI servers including - # wsgiref. - if "date" not in self.headers: - self.headers["Date"] = http_date() - accept_ranges = _clean_accept_ranges(accept_ranges) - is206 = self._process_range_request(environ, complete_length, accept_ranges) - if not is206 and not is_resource_modified( - environ, - self.headers.get("etag"), - None, - self.headers.get("last-modified"), - ): - if parse_etags(environ.get("HTTP_IF_MATCH")): - self.status_code = 412 - else: - self.status_code = 304 - if ( - self.automatically_set_content_length # type: ignore - and "content-length" not in self.headers - ): - length = self.calculate_content_length() # type: ignore - if length is not None: - self.headers["Content-Length"] = length - return self - - def add_etag(self, overwrite: bool = False, weak: bool = False) -> None: - """Add an etag for the current response if there is none yet.""" - if overwrite or "etag" not in self.headers: - self.set_etag(generate_etag(self.get_data()), weak) # type: ignore - - def set_etag(self, etag: str, weak: bool = False) -> None: - """Set the etag, and override the old one if there was one.""" - self.headers["ETag"] = quote_etag(etag, weak) - - def get_etag(self) -> t.Union[t.Tuple[str, bool], t.Tuple[None, None]]: - """Return a tuple in the form ``(etag, is_weak)``. If there is no - ETag the return value is ``(None, None)``. - """ - return unquote_etag(self.headers.get("ETag")) - - def freeze(self, no_etag: bool = False) -> None: - """Call this method if you want to make your response object ready for - pickeling. This buffers the generator if there is one. This also - sets the etag unless `no_etag` is set to `True`. - """ - if not no_etag: - self.add_etag() - super().freeze() # type: ignore - - accept_ranges = header_property[str]( - "Accept-Ranges", - doc="""The `Accept-Ranges` header. Even though the name would - indicate that multiple values are supported, it must be one - string token only. - - The values ``'bytes'`` and ``'none'`` are common. - - .. versionadded:: 0.7""", - ) - - @property - def content_range(self) -> ContentRange: - """The ``Content-Range`` header as a - :class:`~werkzeug.datastructures.ContentRange` object. Available - even if the header is not set. - - .. versionadded:: 0.7 - """ - - def on_update(rng: ContentRange) -> None: - if not rng: - del self.headers["content-range"] - else: - self.headers["Content-Range"] = rng.to_header() - - rv = parse_content_range_header(self.headers.get("content-range"), on_update) - # always provide a content range object to make the descriptor - # more user friendly. It provides an unset() method that can be - # used to remove the header quickly. - if rv is None: - rv = ContentRange(None, None, None, on_update=on_update) - return rv - - @content_range.setter - def content_range(self, value: t.Optional[t.Union[ContentRange, str]]) -> None: - if not value: - del self.headers["content-range"] - elif isinstance(value, str): - self.headers["Content-Range"] = value - else: - self.headers["Content-Range"] = value.to_header() + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wrappers/json.py b/src/werkzeug/wrappers/json.py index df465c90..50bba7a5 100644 --- a/src/werkzeug/wrappers/json.py +++ b/src/werkzeug/wrappers/json.py @@ -1,130 +1,13 @@ -import datetime -import json -import typing as t -import uuid - -from ..exceptions import BadRequest - - -class _JSONModule: - @staticmethod - def _default(o: t.Any) -> t.Any: - if isinstance(o, datetime.date): - return o.isoformat() - - if isinstance(o, uuid.UUID): - return str(o) - - if hasattr(o, "__html__"): - return str(o.__html__()) - - raise TypeError() - - @classmethod - def dumps(cls, obj: t.Any, **kw) -> str: - kw.setdefault("separators", (",", ":")) - kw.setdefault("default", cls._default) - kw.setdefault("sort_keys", True) - return json.dumps(obj, **kw) - - @staticmethod - def loads(s: t.Union[str, bytes], **kw) -> t.Any: - return json.loads(s, **kw) +import warnings class JSONMixin: - """Mixin to parse :attr:`data` as JSON. Can be mixed in for both - :class:`~werkzeug.wrappers.Request` and - :class:`~werkzeug.wrappers.Response` classes. - """ - - #: A module or other object that has ``dumps`` and ``loads`` - #: functions that match the API of the built-in :mod:`json` module. - json_module = _JSONModule - - @property - def json(self) -> t.Optional[t.Any]: - """The parsed JSON data if :attr:`mimetype` indicates JSON - (:mimetype:`application/json`, see :meth:`is_json`). - - Calls :meth:`get_json` with default arguments. - """ - return self.get_json() - - @property - def is_json(self) -> bool: - """Check if the mimetype indicates JSON data, either - :mimetype:`application/json` or :mimetype:`application/*+json`. - """ - mt = self.mimetype # type: ignore - return ( - mt == "application/json" - or mt.startswith("application/") - and mt.endswith("+json") + def __init__(self, *args, **kwargs): + warnings.warn( + "'JSONMixin' is deprecated and will be removed in Werkzeug" + " version 2.1. 'Request' now includes the functionality" + " directly.", + DeprecationWarning, + stacklevel=2, ) - - def _get_data_for_json(self, cache: bool) -> bytes: - try: - return self.get_data(cache=cache) # type: ignore - except TypeError: - # Response doesn't have cache param. - return self.get_data() # type: ignore - - # Cached values for ``(silent=False, silent=True)``. Initialized - # with sentinel values. - _cached_json: t.Tuple[t.Any, t.Any] = (Ellipsis, Ellipsis) - - def get_json( - self, force: bool = False, silent: bool = False, cache: bool = True - ) -> t.Optional[t.Any]: - """Parse :attr:`data` as JSON. - - If the mimetype does not indicate JSON - (:mimetype:`application/json`, see :meth:`is_json`), this - returns ``None``. - - If parsing fails, :meth:`on_json_loading_failed` is called and - its return value is used as the return value. - - :param force: Ignore the mimetype and always try to parse JSON. - :param silent: Silence parsing errors and return ``None`` - instead. - :param cache: Store the parsed JSON to return for subsequent - calls. - """ - if cache and self._cached_json[silent] is not Ellipsis: - return self._cached_json[silent] - - if not (force or self.is_json): - return None - - data = self._get_data_for_json(cache=cache) - - try: - rv = self.json_module.loads(data) - except ValueError as e: - if silent: - rv = None - - if cache: - normal_rv, _ = self._cached_json - self._cached_json = (normal_rv, rv) - else: - rv = self.on_json_loading_failed(e) - - if cache: - _, silent_rv = self._cached_json - self._cached_json = (rv, silent_rv) - else: - if cache: - self._cached_json = (rv, rv) - - return rv - - def on_json_loading_failed(self, e: ValueError) -> t.Any: - """Called if :meth:`get_json` parsing fails and isn't silenced. - If this method returns a value, it is used as the return value - for :meth:`get_json`. The default implementation raises - :exc:`~werkzeug.exceptions.BadRequest`. - """ - raise BadRequest(f"Failed to decode JSON object: {e}") + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wrappers/request.py b/src/werkzeug/wrappers/request.py index 0922922a..449703d0 100644 --- a/src/werkzeug/wrappers/request.py +++ b/src/werkzeug/wrappers/request.py @@ -1,39 +1,1055 @@ -from .accept import AcceptMixin -from .auth import AuthorizationMixin -from .base_request import BaseRequest -from .common_descriptors import CommonRequestDescriptorsMixin -from .cors import CORSRequestMixin -from .etag import ETagRequestMixin -from .user_agent import UserAgentMixin - - -class Request( # type: ignore - BaseRequest, - AcceptMixin, - ETagRequestMixin, - UserAgentMixin, - AuthorizationMixin, - CORSRequestMixin, - CommonRequestDescriptorsMixin, -): - """Full featured request object implementing the following mixins: - - - :class:`AcceptMixin` for accept header parsing - - :class:`ETagRequestMixin` for etag and cache control handling - - :class:`UserAgentMixin` for user agent introspection - - :class:`AuthorizationMixin` for http auth handling - - :class:`~werkzeug.wrappers.cors.CORSRequestMixin` for Cross - Origin Resource Sharing headers - - :class:`CommonRequestDescriptorsMixin` for common headers +import functools +import json +import typing as t +import warnings +from datetime import datetime +from io import BytesIO +from .._internal import _to_str +from .._internal import _wsgi_decoding_dance +from ..datastructures import Accept +from ..datastructures import Authorization +from ..datastructures import CharsetAccept +from ..datastructures import CombinedMultiDict +from ..datastructures import EnvironHeaders +from ..datastructures import ETags +from ..datastructures import FileStorage +from ..datastructures import HeaderSet +from ..datastructures import IfRange +from ..datastructures import ImmutableList +from ..datastructures import ImmutableMultiDict +from ..datastructures import iter_multi_items +from ..datastructures import LanguageAccept +from ..datastructures import MIMEAccept +from ..datastructures import MultiDict +from ..datastructures import Range +from ..datastructures import RequestCacheControl +from ..formparser import default_stream_factory +from ..formparser import FormDataParser +from ..http import parse_accept_header +from ..http import parse_authorization_header +from ..http import parse_cache_control_header +from ..http import parse_cookie +from ..http import parse_date +from ..http import parse_etags +from ..http import parse_if_range_header +from ..http import parse_list_header +from ..http import parse_options_header +from ..http import parse_range_header +from ..http import parse_set_header +from ..urls import url_decode +from ..useragents import UserAgent +from ..utils import cached_property +from ..utils import environ_property +from ..utils import header_property +from ..wsgi import get_content_length +from ..wsgi import get_current_url +from ..wsgi import get_host +from ..wsgi import get_input_stream +from werkzeug.exceptions import BadRequest + +if t.TYPE_CHECKING: + from wsgiref.types import WSGIApplication + from wsgiref.types import WSGIEnvironment + + +class Request: + """Represents an incoming HTTP request, with headers and body taken + from the WSGI environment. Has properties and methods for using the + functionality defined by various HTTP specs. The data in requests + object is read-only. + + Text data is assumed to use UTF-8 encoding, which should be true for + the vast majority of modern clients. Using an encoding set by the + client is unsafe in Python due to extra encodings it provides, such + as ``zip``. To change the assumed encoding, subclass and replace + :attr:`charset`. + + :param environ: The WSGI environ is generated by the WSGI server and + contains information about the server configuration and client + request. + :param populate_request: Add this request object to the WSGI environ + as ``environ['werkzeug.request']``. Can be useful when + debugging. + :param shallow: Makes reading from :attr:`stream` (and any method + that would read from it) raise a :exc:`RuntimeError`. Useful to + prevent consuming the form data in middleware, which would make + it unavailable to the final application. + + .. versionchanged:: 2.0 + Combine ``BaseRequest`` and mixins into a single ``Request`` + class. Using the old classes is deprecated and will be removed + in version 2.1. + + .. versionchanged:: 0.5 + Read-only mode is enforced with immutable classes for all data. """ + #: the charset for the request, defaults to utf-8 + charset = "utf-8" + + #: the error handling procedure for errors, defaults to 'replace' + encoding_errors = "replace" + + #: the maximum content length. This is forwarded to the form data + #: parsing function (:func:`parse_form_data`). When set and the + #: :attr:`form` or :attr:`files` attribute is accessed and the + #: parsing fails because more than the specified value is transmitted + #: a :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised. + #: + #: Have a look at :doc:`/request_data` for more details. + #: + #: .. versionadded:: 0.5 + max_content_length: t.Optional[int] = None + + #: the maximum form field size. This is forwarded to the form data + #: parsing function (:func:`parse_form_data`). When set and the + #: :attr:`form` or :attr:`files` attribute is accessed and the + #: data in memory for post data is longer than the specified value a + #: :exc:`~werkzeug.exceptions.RequestEntityTooLarge` exception is raised. + #: + #: Have a look at :doc:`/request_data` for more details. + #: + #: .. versionadded:: 0.5 + max_form_memory_size: t.Optional[int] = None + + #: 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 + #: possible to use mutable structures, but this is not recommended. + #: + #: .. versionadded:: 0.6 + parameter_storage_class: t.Type[MultiDict] = ImmutableMultiDict + + #: the type to be used for list values from the incoming WSGI environment. + #: By default an :class:`~werkzeug.datastructures.ImmutableList` is used + #: (for example for :attr:`access_list`). + #: + #: .. versionadded:: 0.6 + list_storage_class: t.Type[t.List] = ImmutableList + + #: The type to be used for dict values from the incoming WSGI + #: environment. (For example for :attr:`cookies`.) By default an + #: :class:`~werkzeug.datastructures.ImmutableMultiDict` is used. + #: + #: .. versionchanged:: 1.0.0 + #: Changed to ``ImmutableMultiDict`` to support multiple values. + #: + #: .. versionadded:: 0.6 + dict_storage_class: t.Type[MultiDict] = ImmutableMultiDict + + #: The form data parser that shoud be used. Can be replaced to customize + #: the form date parsing. + form_data_parser_class: t.Type[FormDataParser] = FormDataParser + + #: Optionally a list of hosts that is trusted by this request. By default + #: all hosts are trusted which means that whatever the client sends the + #: host is will be accepted. + #: + #: Because `Host` and `X-Forwarded-Host` headers can be set to any value by + #: a malicious client, it is recommended to either set this property or + #: implement similar validation in the proxy (if application is being run + #: behind one). + #: + #: .. versionadded:: 0.9 + trusted_hosts: t.Optional[t.List[str]] = None + + #: Indicates whether the data descriptor should be allowed to read and + #: buffer up the input stream. By default it's enabled. + #: + #: .. versionadded:: 0.9 + disable_data_descriptor: bool = False + + #: The WSGI environment containing HTTP headers and information from + #: the WSGI server. + environ: "WSGIEnvironment" + + #: Set when creating the request object. If ``True``, reading from + #: the request body will cause a ``RuntimeException``. Useful to + #: prevent modifying the stream from middleware. + shallow: bool + + def __init__( + self, + environ: "WSGIEnvironment", + populate_request: bool = True, + shallow: bool = False, + ) -> None: + self.environ = environ + if populate_request and not shallow: + self.environ["werkzeug.request"] = self + self.shallow = shallow + + def __repr__(self) -> str: + # make sure the __repr__ even works if the request was created + # from an invalid WSGI environment. If we display the request + # in a debug session we don't want the repr to blow up. + args = [] + try: + args.append(f"'{self.url}'") + args.append(f"[{self.method}]") + except Exception: + args.append("(invalid WSGI environ)") + + return f"<{type(self).__name__} {' '.join(args)}>" + + @property + def url_charset(self) -> str: + """The charset that is assumed for URLs. Defaults to the value + of :attr:`charset`. + + .. versionadded:: 0.6 + """ + return self.charset + + @classmethod + def from_values(cls, *args, **kwargs) -> "Request": + """Create a new request object based on the values provided. If + environ is given missing values are filled from there. This method is + useful for small scripts when you need to simulate a request from an URL. + Do not use this method for unittesting, there is a full featured client + object (:class:`Client`) that allows to create multipart requests, + support for cookies etc. + + This accepts the same options as the + :class:`~werkzeug.test.EnvironBuilder`. + + .. versionchanged:: 0.5 + This method now accepts the same arguments as + :class:`~werkzeug.test.EnvironBuilder`. Because of this the + `environ` parameter is now called `environ_overrides`. + + :return: request object + """ + from ..test import EnvironBuilder + + charset = kwargs.pop("charset", cls.charset) + kwargs["charset"] = charset + builder = EnvironBuilder(*args, **kwargs) + try: + return builder.get_request(cls) + finally: + builder.close() + + @classmethod + def application( + cls, f: t.Callable[["Request"], "WSGIApplication"] + ) -> "WSGIApplication": + """Decorate a function as responder that accepts the request as + the last argument. This works like the :func:`responder` + decorator but the function is passed the request object as the + last argument and the request object will be closed + automatically:: + + @Request.application + def my_wsgi_app(request): + return Response('Hello World!') + + As of Werkzeug 0.14 HTTP exceptions are automatically caught and + converted to responses instead of failing. + + :param f: the WSGI callable to decorate + :return: a new WSGI callable + """ + #: return a callable that wraps the -2nd argument with the request + #: and calls the function with all the arguments up to that one and + #: the request. The return value is then called with the latest + #: two arguments. This makes it possible to use this decorator for + #: both standalone WSGI functions as well as bound methods and + #: partially applied functions. + from ..exceptions import HTTPException + + @functools.wraps(f) + def application(*args): + request = cls(args[-2]) + with request: + try: + resp = f(*args[:-2] + (request,)) + except HTTPException as e: + resp = e.get_response(args[-2]) + return resp(*args[-2:]) + + return application + + def _get_file_stream( + self, + total_content_length: int, + content_type: t.Optional[str], + filename: t.Optional[str] = None, + content_length: t.Optional[int] = None, + ): + """Called to get a stream for the file upload. + + This must provide a file-like class with `read()`, `readline()` + and `seek()` methods that is both writeable and readable. + + The default implementation returns a temporary file if the total + content length is higher than 500KB. Because many browsers do not + provide a content length for the files only the total content + length matters. + + :param total_content_length: the total content length of all the + data in the request combined. This value + is guaranteed to be there. + :param content_type: the mimetype of the uploaded file. + :param filename: the filename of the uploaded file. May be `None`. + :param content_length: the length of this file. This value is usually + not provided because webbrowsers do not provide + this value. + """ + return default_stream_factory( + total_content_length=total_content_length, + filename=filename, + content_type=content_type, + content_length=content_length, + ) + + @property + def want_form_data_parsed(self) -> bool: + """Returns True if the request method carries content. As of + Werkzeug 0.9 this will be the case if a content type is transmitted. + + .. versionadded:: 0.8 + """ + return bool(self.environ.get("CONTENT_TYPE")) + + def make_form_data_parser(self) -> FormDataParser: + """Creates the form data parser. Instantiates the + :attr:`form_data_parser_class` with some parameters. + + .. versionadded:: 0.8 + """ + return self.form_data_parser_class( + self._get_file_stream, + self.charset, + self.encoding_errors, + self.max_form_memory_size, + self.max_content_length, + self.parameter_storage_class, + ) + + def _load_form_data(self) -> None: + """Method used internally to retrieve submitted data. After calling + this sets `form` and `files` on the request object to multi dicts + filled with the incoming form data. As a matter of fact the input + stream will be empty afterwards. You can also call this method to + force the parsing of the form data. + + .. versionadded:: 0.8 + """ + # abort early if we have already consumed the stream + if "form" in self.__dict__: + return + + _assert_not_shallow(self) + + if self.want_form_data_parsed: + content_type = self.environ.get("CONTENT_TYPE", "") + content_length = get_content_length(self.environ) + mimetype, options = parse_options_header(content_type) + parser = self.make_form_data_parser() + data = parser.parse( + self._get_stream_for_parsing(), mimetype, content_length, options + ) + else: + data = ( + self.stream, + self.parameter_storage_class(), + self.parameter_storage_class(), + ) + + # inject the values into the instance dict so that we bypass + # our cached_property non-data descriptor. + d = self.__dict__ + d["stream"], d["form"], d["files"] = data + + def _get_stream_for_parsing(self) -> t.BinaryIO: + """This is the same as accessing :attr:`stream` with the difference + that if it finds cached data from calling :meth:`get_data` first it + will create a new stream out of the cached data. + + .. versionadded:: 0.9.3 + """ + cached_data = getattr(self, "_cached_data", None) + if cached_data is not None: + return BytesIO(cached_data) + return self.stream + + def close(self) -> None: + """Closes associated resources of this request object. This + closes all file handles explicitly. You can also use the request + object in a with statement which will automatically close it. + + .. versionadded:: 0.9 + """ + files = self.__dict__.get("files") + for _key, value in iter_multi_items(files or ()): + value.close() + + def __enter__(self) -> "Request": + return self + + def __exit__(self, exc_type, exc_value, tb) -> None: + self.close() + + @cached_property + def stream(self) -> t.BinaryIO: + """ + If the incoming form data was not encoded with a known mimetype + the data is stored unmodified in this stream for consumption. Most + of the time it is a better idea to use :attr:`data` which will give + you that data as a string. The stream only returns the data once. + + Unlike :attr:`input_stream` this stream is properly guarded that you + can't accidentally read past the length of the input. Werkzeug will + internally always refer to this stream to read data which makes it + possible to wrap this object with a stream that does filtering. + + .. versionchanged:: 0.9 + This stream is now always available but might be consumed by the + form parser later on. Previously the stream was only set if no + parsing happened. + """ + _assert_not_shallow(self) + return get_input_stream(self.environ) + + input_stream = environ_property( + "wsgi.input", + """The WSGI input stream. + + In general it's a bad idea to use this one because you can + easily read past the boundary. Use the :attr:`stream` + instead.""", + ) + + @cached_property + def args(self) -> "MultiDict[str, str]": + """The parsed URL parameters (the part in the URL after the question + mark). + + By default an + :class:`~werkzeug.datastructures.ImmutableMultiDict` + is returned from this function. This can be changed by setting + :attr:`parameter_storage_class` to a different type. This might + be necessary if the order of the form data is important. + """ + return url_decode( + self.environ.get("QUERY_STRING", "").encode("latin1"), + self.url_charset, + errors=self.encoding_errors, + cls=self.parameter_storage_class, + ) + + @cached_property + def data(self) -> bytes: + """ + Contains the incoming request data as string in case it came with + a mimetype Werkzeug does not handle. + """ + + if self.disable_data_descriptor: + raise AttributeError("data descriptor is disabled") + # XXX: this should eventually be deprecated. + + # We trigger form data parsing first which means that the descriptor + # will not cache the data that would otherwise be .form or .files + # data. This restores the behavior that was there in Werkzeug + # before 0.9. New code should use :meth:`get_data` explicitly as + # this will make behavior explicit. + return self.get_data(parse_form_data=True) + + def get_data( + self, cache: bool = True, as_text: bool = False, parse_form_data: bool = False + ) -> bytes: + """This reads the buffered incoming data from the client into one + bytes object. By default this is cached but that behavior can be + changed by setting `cache` to `False`. + + Usually it's a bad idea to call this method without checking the + content length first as a client could send dozens of megabytes or more + to cause memory problems on the server. + + Note that if the form data was already parsed this method will not + return anything as form data parsing does not cache the data like + this method does. To implicitly invoke form data parsing function + set `parse_form_data` to `True`. When this is done the return value + of this method will be an empty string if the form parser handles + the data. This generally is not necessary as if the whole data is + cached (which is the default) the form parser will used the cached + data to parse the form data. Please be generally aware of checking + the content length first in any case before calling this method + to avoid exhausting server memory. + + If `as_text` is set to `True` the return value will be a decoded + string. + + .. versionadded:: 0.9 + """ + rv = getattr(self, "_cached_data", None) + if rv is None: + if parse_form_data: + self._load_form_data() + rv = self.stream.read() + if cache: + self._cached_data = rv + if as_text: + rv = rv.decode(self.charset, self.encoding_errors) + return rv + + @cached_property + def form(self) -> "ImmutableMultiDict[str, str]": + """The form parameters. By default an + :class:`~werkzeug.datastructures.ImmutableMultiDict` + is returned from this function. This can be changed by setting + :attr:`parameter_storage_class` to a different type. This might + be necessary if the order of the form data is important. + + Please keep in mind that file uploads will not end up here, but instead + in the :attr:`files` attribute. + + .. versionchanged:: 0.9 + + Previous to Werkzeug 0.9 this would only contain form data for POST + and PUT requests. + """ + self._load_form_data() + return self.form + + @cached_property + def values(self) -> "CombinedMultiDict[str, str]": + """A :class:`werkzeug.datastructures.CombinedMultiDict` that combines + :attr:`args` and :attr:`form`.""" + args = [] + for d in self.args, self.form: + if not isinstance(d, MultiDict): + d = MultiDict(d) + args.append(d) + return CombinedMultiDict(args) + + @cached_property + def files(self) -> "ImmutableMultiDict[str, FileStorage]": + """:class:`~werkzeug.datastructures.MultiDict` object containing + all uploaded files. Each key in :attr:`files` is the name from the + ``<input type="file" name="">``. Each value in :attr:`files` is a + Werkzeug :class:`~werkzeug.datastructures.FileStorage` object. + + It basically behaves like a standard file object you know from Python, + with the difference that it also has a + :meth:`~werkzeug.datastructures.FileStorage.save` function that can + store the file on the filesystem. + + Note that :attr:`files` will only contain data if the request method was + POST, PUT or PATCH and the ``<form>`` that posted to the request had + ``enctype="multipart/form-data"``. It will be empty otherwise. + + See the :class:`~werkzeug.datastructures.MultiDict` / + :class:`~werkzeug.datastructures.FileStorage` documentation for + more details about the used data structure. + """ + self._load_form_data() + return self.files + + @cached_property + def cookies(self) -> "ImmutableMultiDict[str, str]": + """A :class:`dict` with the contents of all cookies transmitted with + the request.""" + return parse_cookie( # type: ignore + self.environ, + self.charset, + self.encoding_errors, + cls=self.dict_storage_class, + ) + + @cached_property + def headers(self) -> EnvironHeaders: + """The headers from the WSGI environ as immutable + :class:`~werkzeug.datastructures.EnvironHeaders`. + """ + return EnvironHeaders(self.environ) + + @cached_property + def path(self) -> str: + """Requested path. This works a bit like the regular path + info in the WSGI environment but will always include a leading slash, + even if the URL root is accessed. + """ + raw_path = _wsgi_decoding_dance( + self.environ.get("PATH_INFO") or "", self.charset, self.encoding_errors + ) + return "/" + raw_path.lstrip("/") + + @cached_property + def full_path(self) -> str: + """Requested path, including the query string.""" + return f"{self.path}?{_to_str(self.query_string, self.url_charset)}" + + @cached_property + def script_root(self) -> str: + """The root path of the script without the trailing slash.""" + raw_path = _wsgi_decoding_dance( + self.environ.get("SCRIPT_NAME") or "", self.charset, self.encoding_errors + ) + return raw_path.rstrip("/") + + @cached_property + def url(self) -> str: + """The reconstructed current URL as IRI. + See also: :attr:`trusted_hosts`. + """ + return get_current_url(self.environ, trusted_hosts=self.trusted_hosts) + + @cached_property + def base_url(self) -> str: + """Like :attr:`url` but without the querystring + See also: :attr:`trusted_hosts`. + """ + return get_current_url( + self.environ, strip_querystring=True, trusted_hosts=self.trusted_hosts + ) + + @cached_property + def url_root(self) -> str: + """The full URL root (with hostname), this is the application + root as IRI. + See also: :attr:`trusted_hosts`. + """ + return get_current_url(self.environ, True, trusted_hosts=self.trusted_hosts) + + @cached_property + def host_url(self) -> str: + """Just the host with scheme as IRI. + See also: :attr:`trusted_hosts`. + """ + return get_current_url( + self.environ, host_only=True, trusted_hosts=self.trusted_hosts + ) + + @cached_property + def host(self) -> str: + """Just the host including the port if available. + See also: :attr:`trusted_hosts`. + """ + return get_host(self.environ, trusted_hosts=self.trusted_hosts) + + query_string = environ_property[bytes]( + "QUERY_STRING", + b"", + load_func=lambda x: x.encode("latin1"), + doc="The URL parameters as raw bytes.", + ) + method = environ_property( + "REQUEST_METHOD", + "GET", + load_func=lambda x: x.upper(), + doc="The request method. (For example ``'GET'`` or ``'POST'``).", + ) + + @cached_property + def access_route(self) -> t.List[str]: + """If a forwarded header exists this is a list of all ip addresses + from the client ip to the last proxy server. + """ + if "HTTP_X_FORWARDED_FOR" in self.environ: + return self.list_storage_class( + parse_list_header(self.environ["HTTP_X_FORWARDED_FOR"]) + ) + elif "REMOTE_ADDR" in self.environ: + return self.list_storage_class([self.environ["REMOTE_ADDR"]]) + return self.list_storage_class() + + @property + def remote_addr(self) -> t.Optional[str]: + """The remote address of the client.""" + return self.environ.get("REMOTE_ADDR") + + remote_user = environ_property[str]( + "REMOTE_USER", + doc="""If the server supports user authentication, and the + script is protected, this attribute contains the username the + user has authenticated as.""", + ) + scheme = environ_property[str]( + "wsgi.url_scheme", + doc=""" + URL scheme (http or https). + + .. versionadded:: 0.7""", + ) + is_secure = property( + lambda self: self.environ["wsgi.url_scheme"] == "https", + doc="`True` if the request is secure.", + ) + is_multithread = environ_property[bool]( + "wsgi.multithread", + doc="""boolean that is `True` if the application is served by a + multithreaded WSGI server.""", + ) + is_multiprocess = environ_property[bool]( + "wsgi.multiprocess", + doc="""boolean that is `True` if the application is served by a + WSGI server that spawns multiple processes.""", + ) + is_run_once = environ_property[bool]( + "wsgi.run_once", + doc="""boolean that is `True` if the application will be + executed only once in a process lifetime. This is the case for + CGI for example, but it's not guaranteed that the execution only + happens one time.""", + ) + + # JSON + + #: A module or other object that has ``dumps`` and ``loads`` + #: functions that match the API of the built-in :mod:`json` module. + json_module = json + + @property + def json(self) -> t.Optional[t.Any]: + """The parsed JSON data if :attr:`mimetype` indicates JSON + (:mimetype:`application/json`, see :meth:`is_json`). + + Calls :meth:`get_json` with default arguments. + """ + return self.get_json() + + @property + def is_json(self) -> bool: + """Check if the mimetype indicates JSON data, either + :mimetype:`application/json` or :mimetype:`application/*+json`. + """ + mt = self.mimetype + return ( + mt == "application/json" + or mt.startswith("application/") + and mt.endswith("+json") + ) + + # Cached values for ``(silent=False, silent=True)``. Initialized + # with sentinel values. + _cached_json: t.Tuple[t.Any, t.Any] = (Ellipsis, Ellipsis) + + def get_json( + self, force: bool = False, silent: bool = False, cache: bool = True + ) -> t.Optional[t.Any]: + """Parse :attr:`data` as JSON. + + If the mimetype does not indicate JSON + (:mimetype:`application/json`, see :meth:`is_json`), this + returns ``None``. + + If parsing fails, :meth:`on_json_loading_failed` is called and + its return value is used as the return value. + + :param force: Ignore the mimetype and always try to parse JSON. + :param silent: Silence parsing errors and return ``None`` + instead. + :param cache: Store the parsed JSON to return for subsequent + calls. + """ + if cache and self._cached_json[silent] is not Ellipsis: + return self._cached_json[silent] + + if not (force or self.is_json): + return None + + data = self.get_data(cache=cache) + + try: + rv = self.json_module.loads(data) + except ValueError as e: + if silent: + rv = None + + if cache: + normal_rv, _ = self._cached_json + self._cached_json = (normal_rv, rv) + else: + rv = self.on_json_loading_failed(e) + + if cache: + _, silent_rv = self._cached_json + self._cached_json = (rv, silent_rv) + else: + if cache: + self._cached_json = (rv, rv) + + return rv + + def on_json_loading_failed(self, e: ValueError) -> t.Any: + """Called if :meth:`get_json` parsing fails and isn't silenced. + If this method returns a value, it is used as the return value + for :meth:`get_json`. The default implementation raises + :exc:`~werkzeug.exceptions.BadRequest`. + """ + raise BadRequest(f"Failed to decode JSON object: {e}") + + # Common Descriptors + + content_type = header_property[str]( + "Content-Type", + doc="""The Content-Type entity-header field indicates the media + type of the entity-body sent to the recipient or, in the case of + the HEAD method, the media type that would have been sent had + the request been a GET.""", + read_only=True, + ) + + @cached_property + def content_length(self) -> t.Optional[int]: + """The Content-Length entity-header field indicates the size of the + entity-body in bytes or, in the case of the HEAD method, the size of + the entity-body that would have been sent had the request been a + GET. + """ + return get_content_length(self.headers) + + content_encoding = header_property[str]( + "Content-Encoding", + doc="""The Content-Encoding entity-header field is used as a + modifier to the media-type. When present, its value indicates + what additional content codings have been applied to the + entity-body, and thus what decoding mechanisms must be applied + in order to obtain the media-type referenced by the Content-Type + header field. + + .. versionadded:: 0.9""", + read_only=True, + ) + content_md5 = header_property[str]( + "Content-MD5", + doc="""The Content-MD5 entity-header field, as defined in + RFC 1864, is an MD5 digest of the entity-body for the purpose of + providing an end-to-end message integrity check (MIC) of the + entity-body. (Note: a MIC is good for detecting accidental + modification of the entity-body in transit, but is not proof + against malicious attacks.) + + .. versionadded:: 0.9""", + read_only=True, + ) + referrer = header_property[str]( + "Referer", + doc="""The Referer[sic] request-header field allows the client + to specify, for the server's benefit, the address (URI) of the + resource from which the Request-URI was obtained (the + "referrer", although the header field is misspelled).""", + read_only=True, + ) + date = header_property( + "Date", + None, + parse_date, + doc="""The Date general-header field represents the date and + time at which the message was originated, having the same + semantics as orig-date in RFC 822.""", + read_only=True, + ) + max_forwards = header_property( + "Max-Forwards", + None, + int, + doc="""The Max-Forwards request-header field provides a + mechanism with the TRACE and OPTIONS methods to limit the number + of proxies or gateways that can forward the request to the next + inbound server.""", + read_only=True, + ) + + def _parse_content_type(self) -> None: + if not hasattr(self, "_parsed_content_type"): + self._parsed_content_type = parse_options_header( + self.headers.get("Content-Type", "") + ) + + @property + 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 + ``'text/html'``. + """ + self._parse_content_type() + return self._parsed_content_type[0].lower() + + @property + def mimetype_params(self) -> t.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'}``. + """ + self._parse_content_type() + return self._parsed_content_type[1] + + @cached_property + def pragma(self) -> HeaderSet: + """The Pragma general-header field is used to include + implementation-specific directives that might apply to any recipient + along the request/response chain. All pragma directives specify + optional behavior from the viewpoint of the protocol; however, some + systems MAY require that behavior be consistent with the directives. + """ + return parse_set_header(self.headers.get("Pragma", "")) + + # Accept + + @cached_property + def accept_mimetypes(self) -> MIMEAccept: + """List of mimetypes this client supports as + :class:`~werkzeug.datastructures.MIMEAccept` object. + """ + return parse_accept_header(self.headers.get("Accept"), MIMEAccept) + + @cached_property + def accept_charsets(self) -> CharsetAccept: + """List of charsets this client supports as + :class:`~werkzeug.datastructures.CharsetAccept` object. + """ + return parse_accept_header(self.headers.get("Accept-Charset"), CharsetAccept) + + @cached_property + def accept_encodings(self) -> Accept: + """List of encodings this client accepts. Encodings in a HTTP term + are compression encodings such as gzip. For charsets have a look at + :attr:`accept_charset`. + """ + return parse_accept_header(self.headers.get("Accept-Encoding")) + + @cached_property + def accept_languages(self) -> LanguageAccept: + """List of languages this client accepts as + :class:`~werkzeug.datastructures.LanguageAccept` object. + + .. versionchanged 0.5 + In previous versions this was a regular + :class:`~werkzeug.datastructures.Accept` object. + """ + return parse_accept_header(self.headers.get("Accept-Language"), LanguageAccept) + + # ETag + + @cached_property + def cache_control(self) -> RequestCacheControl: + """A :class:`~werkzeug.datastructures.RequestCacheControl` object + for the incoming cache control headers. + """ + cache_control = self.headers.get("Cache-Control") + return parse_cache_control_header(cache_control, None, RequestCacheControl) + + @cached_property + def if_match(self) -> ETags: + """An object containing all the etags in the `If-Match` header. + + :rtype: :class:`~werkzeug.datastructures.ETags` + """ + return parse_etags(self.headers.get("If-Match")) + + @cached_property + def if_none_match(self) -> ETags: + """An object containing all the etags in the `If-None-Match` header. + + :rtype: :class:`~werkzeug.datastructures.ETags` + """ + return parse_etags(self.headers.get("If-None-Match")) + + @cached_property + def if_modified_since(self) -> t.Optional[datetime]: + """The parsed `If-Modified-Since` header as datetime object.""" + return parse_date(self.headers.get("If-Modified-Since")) + + @cached_property + def if_unmodified_since(self) -> t.Optional[datetime]: + """The parsed `If-Unmodified-Since` header as datetime object.""" + return parse_date(self.headers.get("If-Unmodified-Since")) + + @cached_property + def if_range(self) -> IfRange: + """The parsed `If-Range` header. + + .. versionadded:: 0.7 + + :rtype: :class:`~werkzeug.datastructures.IfRange` + """ + return parse_if_range_header(self.headers.get("If-Range")) + + @cached_property + def range(self) -> t.Optional[Range]: + """The parsed `Range` header. + + .. versionadded:: 0.7 + + :rtype: :class:`~werkzeug.datastructures.Range` + """ + return parse_range_header(self.headers.get("Range")) + + # User Agent + + @cached_property + def user_agent(self) -> UserAgent: + """The current user agent.""" + return UserAgent(self.headers.get("User-Agent", "")) + + # Authorization + + @cached_property + def authorization(self) -> t.Optional[Authorization]: + """The `Authorization` object in parsed form.""" + return parse_authorization_header(self.headers.get("Authorization")) + + # CORS + + origin = header_property[str]( + "Origin", + doc=( + "The host that the request originated from. Set" + " :attr:`~CORSResponseMixin.access_control_allow_origin` on" + " the response to indicate which origins are allowed." + ), + read_only=True, + ) + + access_control_request_headers = header_property( + "Access-Control-Request-Headers", + load_func=parse_set_header, + doc=( + "Sent with a preflight request to indicate which headers" + " will be sent with the cross origin request. Set" + " :attr:`~CORSResponseMixin.access_control_allow_headers`" + " on the response to indicate which headers are allowed." + ), + read_only=True, + ) + + access_control_request_method = header_property[str]( + "Access-Control-Request-Method", + doc=( + "Sent with a preflight request to indicate which method" + " will be used for the cross origin request. Set" + " :attr:`~CORSResponseMixin.access_control_allow_methods`" + " on the response to indicate which methods are allowed." + ), + read_only=True, + ) + + +def _assert_not_shallow(request: Request) -> None: + if request.shallow: + raise RuntimeError( + "A shallow request tried to consume form data. If you really" + " want to do that, set `shallow` to False." + ) + class StreamOnlyMixin: - """If mixed in before the request object this will change the behavior - of it to disable handling of form parsing. This disables the - :attr:`files`, :attr:`form` attributes and will just provide a - :attr:`stream` attribute that however is always available. + """Mixin to create a ``Request`` that disables the ``data``, + ``form``, and ``files`` properties. Only ``stream`` is available. + + .. deprecated:: 2.0 + Will be removed in 2.1. You likely want to create the request + with ``shallow=True`` instead. Or subclass and set + ``disable_data_descriptor`` and ``want_form_data_parsed``. .. versionadded:: 0.9 """ @@ -41,9 +1057,39 @@ class StreamOnlyMixin: disable_data_descriptor = True want_form_data_parsed = False + def __init__(self, *args, **kwargs): + warnings.warn( + "'StreamOnlyMixin' is deprecated and will be removed in" + " Werkzeug version 2.1. Create the request with" + " 'shallow=True' instead.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) -class PlainRequest(StreamOnlyMixin, Request): # type: ignore - """A request object without special form parsing capabilities. + +class PlainRequest(StreamOnlyMixin, Request): + """A request object without ``data``, ``form``, and ``files``. + + .. deprecated:: 2.0 + Will be removed in 2.1. You likely want to create the request + with ``shallow=True`` instead. Or subclass and set + ``disable_data_descriptor`` and ``want_form_data_parsed``. .. versionadded:: 0.9 """ + + def __init__(self, *args, **kwargs): + warnings.warn( + "'PlainRequest' is deprecated and will be removed in" + " Werkzeug version 2.1. Create the request with" + " 'shallow=True' instead.", + DeprecationWarning, + stacklevel=2, + ) + + # Don't show the DeprecationWarning for StreamOnlyMixin. + with warnings.catch_warnings(): + # Don't show the DeprecationWarning for StreamOnlyMixin. + warnings.simplefilter("ignore", DeprecationWarning) + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wrappers/response.py b/src/werkzeug/wrappers/response.py index f34261a8..9d278100 100644 --- a/src/werkzeug/wrappers/response.py +++ b/src/werkzeug/wrappers/response.py @@ -1,11 +1,1368 @@ +import json +import typing import typing as t +import warnings +from datetime import datetime +from datetime import timedelta +from .._internal import _to_bytes +from .._internal import _to_str +from ..datastructures import Headers +from ..http import dump_cookie +from ..http import HTTP_STATUS_CODES +from ..http import remove_entity_headers +from ..urls import iri_to_uri +from ..urls import url_join from ..utils import cached_property -from .auth import WWWAuthenticateMixin -from .base_response import BaseResponse -from .common_descriptors import CommonResponseDescriptorsMixin -from .cors import CORSResponseMixin -from .etag import ETagResponseMixin +from ..utils import get_content_type +from ..wsgi import ClosingIterator +from ..wsgi import get_current_url +from werkzeug._internal import _get_environ +from werkzeug.datastructures import CallbackDict +from werkzeug.datastructures import ContentRange +from werkzeug.datastructures import ResponseCacheControl +from werkzeug.datastructures import WWWAuthenticate +from werkzeug.http import dump_age +from werkzeug.http import dump_csp_header +from werkzeug.http import dump_header +from werkzeug.http import dump_options_header +from werkzeug.http import generate_etag +from werkzeug.http import http_date +from werkzeug.http import is_resource_modified +from werkzeug.http import parse_age +from werkzeug.http import parse_cache_control_header +from werkzeug.http import parse_content_range_header +from werkzeug.http import parse_csp_header +from werkzeug.http import parse_date +from werkzeug.http import parse_etags +from werkzeug.http import parse_options_header +from werkzeug.http import parse_range_header +from werkzeug.http import parse_set_header +from werkzeug.http import parse_www_authenticate_header +from werkzeug.http import quote_etag +from werkzeug.http import unquote_etag +from werkzeug.utils import header_property +from werkzeug.wsgi import _RangeWrapper + +if t.TYPE_CHECKING: + from wsgiref.types import StartResponse + from wsgiref.types import WSGIApplication + from wsgiref.types import WSGIEnvironment + + +def _warn_if_string(iterable: t.Iterable) -> None: + """Helper for the response objects to check if the iterable returned + to the WSGI server is not a string. + """ + if isinstance(iterable, str): + warnings.warn( + "Response iterable was set to a string. This will appear to" + " work but means that the server will send the data to the" + " client one character at a time. This is almost never" + " intended behavior, use 'response.data' to assign strings" + " to the response object.", + stacklevel=2, + ) + + +def _iter_encoded( + iterable: t.Iterable[t.Union[str, bytes]], charset: str +) -> t.Iterator[bytes]: + for item in iterable: + if isinstance(item, str): + yield item.encode(charset) + else: + yield item + + +def _clean_accept_ranges(accept_ranges: t.Union[bool, str]) -> str: + if accept_ranges is True: + return "bytes" + elif accept_ranges is False: + return "none" + elif isinstance(accept_ranges, str): + return accept_ranges + raise ValueError("Invalid accept_ranges value") + + +def _set_property(name: str, doc: t.Optional[str] = None) -> property: + def fget(self): + def on_update(header_set): + if not header_set and name in self.headers: + del self.headers[name] + elif header_set: + self.headers[name] = header_set.to_header() + + return parse_set_header(self.headers.get(name), on_update) + + def fset(self, value): + if not value: + del self.headers[name] + elif isinstance(value, str): + self.headers[name] = value + else: + self.headers[name] = dump_header(value) + + return property(fget, fset, doc=doc) + + +class Response: + """Represents an outgoing HTTP response with body, status, and + headers. Has properties and methods for using the + functionality defined by various HTTP specs. + + The response body is flexible to support different use cases. The + simple form is passing bytes, or a string which will be encoded as + UTF-8. Passing an iterable of bytes or strings makes this a + streaming response. A generator is particularly useful for building + a CSV file in memory or using SSE (Server Sent Events). A file-like + object is also iterable, although the + :func:`~werkzeug.utils.send_file` helper should be used in that + case. + + The response object is itself a WSGI application callable. When + called (:meth:`__call__`) with ``environ`` and ``start_response``, + it will pass its status and headers to ``start_response`` then + return its body as an iterable. + + .. code-block:: python + + from werkzeug.wrappers.response import Response + + def index(): + return Response("Hello, World!") + + def application(environ, start_response): + path = environ.get("PATH_INFO") or "/" + + if path == "/": + response = index() + else: + response = Response("Not Found", status=404) + + return response(environ, start_response) + + :param response: The data for the body of the response. A string or + bytes, or tuple or list of strings or bytes, for a fixed-length + response, or any other iterable of strings or bytes for a + streaming response. Defaults to an empty body. + :param status: The status code for the response. Either an int, in + which case the default status message is added, or a string in + the form ``{code} {message}``, like ``404 Not Found``. Defaults + to 200. + :param headers: A :class:`~werkzeug.datastructures.Headers` object, + or a list of ``(key, value)`` tuples that will be converted to a + ``Headers`` object. + :param mimetype: The mime type (content type without charset or + other parameters) of the response. If the value starts with + ``text/`` (or matches some other special cases), the charset + will be added to create the ``content_type``. + :param content_type: The full content type of the response. + Overrides building the value from ``mimetype``. + :param direct_passthrough: Pass the response body directly through + as the WSGI iterable. This can be used when the body is a binary + file or other iterator of bytes, to skip some unnecessary + checks. Use :func:`~werkzeug.utils.send_file` instead of setting + this manually. + + .. versionchanged:: 2.0 + Combine ``BaseResponse`` and mixins into a single ``Response`` + class. Using the old classes is deprecated and will be removed + in version 2.1. + + .. versionchanged:: 0.5 + The ``direct_passthrough`` parameter was added. + """ + + #: the charset of the response. + charset = "utf-8" + + #: the default status if none is provided. + default_status = 200 + + #: the default mimetype if none is provided. + default_mimetype = "text/plain" + + #: if set to `False` accessing properties on the response object will + #: not try to consume the response iterator and convert it into a list. + #: + #: .. versionadded:: 0.6.2 + #: + #: That attribute was previously called `implicit_seqence_conversion`. + #: (Notice the typo). If you did use this feature, you have to adapt + #: your code to the name change. + implicit_sequence_conversion = True + + #: Should this response object correct the location header to be RFC + #: conformant? This is true by default. + #: + #: .. versionadded:: 0.8 + autocorrect_location_header = True + + #: Should this response object automatically set the content-length + #: header if possible? This is true by default. + #: + #: .. versionadded:: 0.8 + automatically_set_content_length = True + + #: Warn if a cookie header exceeds this size. The default, 4093, should be + #: safely `supported by most browsers <cookie_>`_. A cookie larger than + #: this size will still be sent, but it may be ignored or handled + #: incorrectly by some browsers. Set to 0 to disable this check. + #: + #: .. versionadded:: 0.13 + #: + #: .. _`cookie`: http://browsercookielimits.squawky.net/ + max_cookie_size = 4093 + + #: The response body to send as the WSGI iterable. A list of strings + #: or bytes represents a fixed-length response, any other iterable + #: is a streaming response. Strings are encoded to bytes as UTF-8. + #: + #: Do not set to a plain string or bytes, that will cause sending + #: the response to be very inefficient as it will iterate one byte + #: at a time. + response: t.Union[t.Iterable[str], t.Iterable[bytes]] + + # A :class:`Headers` object representing the response headers. + headers: Headers + + def __init__( + self, + response: t.Optional[ + t.Union[t.Iterable[bytes], bytes, t.Iterable[str], str] + ] = None, + status: t.Optional[t.Union[int, str]] = None, + headers: t.Optional[ + t.Union[ + t.Mapping[str, t.Union[str, int, t.Iterable[t.Union[str, int]]]], + t.Iterable[t.Tuple[str, t.Union[str, int]]], + ] + ] = None, + mimetype: t.Optional[str] = None, + content_type: t.Optional[str] = None, + direct_passthrough: bool = False, + ) -> None: + if isinstance(headers, Headers): + self.headers = headers + elif not headers: + self.headers = Headers() + else: + self.headers = Headers(headers) + + if content_type is None: + if mimetype is None and "content-type" not in self.headers: + mimetype = self.default_mimetype + if mimetype is not None: + mimetype = get_content_type(mimetype, self.charset) + content_type = mimetype + if content_type is not None: + self.headers["Content-Type"] = content_type + if status is None: + status = self.default_status + self.status = status # type: ignore + + #: Pass the response body directly through as the WSGI iterable. + #: This can be used when the body is a binary file or other + #: iterator of bytes, to skip some unnecessary checks. Use + #: :func:`~werkzeug.utils.send_file` instead of setting this + #: manually. + self.direct_passthrough = direct_passthrough + self._on_close: t.List[t.Callable[[], t.Any]] = [] + + # we set the response after the headers so that if a class changes + # the charset attribute, the data is set in the correct charset. + if response is None: + self.response = [] + elif isinstance(response, (str, bytes, bytearray)): + self.set_data(response) + else: + self.response = response + + def call_on_close(self, func: t.Callable[[], t.Any]) -> t.Callable[[], t.Any]: + """Adds a function to the internal list of functions that should + be called as part of closing down the response. Since 0.7 this + function also returns the function that was passed so that this + can be used as a decorator. + + .. versionadded:: 0.6 + """ + self._on_close.append(func) + return func + + def __repr__(self) -> str: + if self.is_sequence: + body_info = f"{sum(map(len, self.iter_encoded()))} bytes" + else: + body_info = "streamed" if self.is_streamed else "likely-streamed" + return f"<{type(self).__name__} {body_info} [{self.status}]>" + + @classmethod + def force_type( + cls, response: "Response", environ: t.Optional["WSGIEnvironment"] = None + ) -> "Response": + """Enforce that the WSGI response is a response object of the current + type. Werkzeug will use the :class:`Response` internally in many + situations like the exceptions. If you call :meth:`get_response` on an + exception you will get back a regular :class:`Response` object, even + if you are using a custom subclass. + + This method can enforce a given response type, and it will also + convert arbitrary WSGI callables into response objects if an environ + is provided:: + + # convert a Werkzeug response object into an instance of the + # MyResponseClass subclass. + response = MyResponseClass.force_type(response) + + # convert any WSGI application into a response object + response = MyResponseClass.force_type(response, environ) + + This is especially useful if you want to post-process responses in + the main dispatcher and use functionality provided by your subclass. + + Keep in mind that this will modify response objects in place if + possible! + + :param response: a response object or wsgi application. + :param environ: a WSGI environment object. + :return: a response object. + """ + if not isinstance(response, Response): + if environ is None: + raise TypeError( + "cannot convert WSGI application into response" + " objects without an environ" + ) + + from ..test import run_wsgi_app + + response = Response(*run_wsgi_app(response, environ)) + + response.__class__ = cls + return response + + @classmethod + def from_app( + cls, app: "WSGIApplication", environ: "WSGIEnvironment", buffered: bool = False + ) -> "Response": + """Create a new response object from an application output. This + works best if you pass it an application that returns a generator all + the time. Sometimes applications may use the `write()` callable + returned by the `start_response` function. This tries to resolve such + edge cases automatically. But if you don't get the expected output + you should set `buffered` to `True` which enforces buffering. + + :param app: the WSGI application to execute. + :param environ: the WSGI environment to execute against. + :param buffered: set to `True` to enforce buffering. + :return: a response object. + """ + from ..test import run_wsgi_app + + return cls(*run_wsgi_app(app, environ, buffered)) + + @property + def status_code(self) -> int: + """The HTTP status code as a number.""" + return self._status_code + + @status_code.setter + def status_code(self, code: int) -> None: + self.status = code # type: ignore + + @property + def status(self) -> str: + """The HTTP status code as a string.""" + return self._status + + @status.setter + def status(self, value: t.Union[str, int]) -> None: + if not isinstance(value, (str, bytes, int)): + raise TypeError("Invalid status argument") + + self._status, self._status_code = self._clean_status(value) + + def _clean_status(self, value: t.Union[str, int]) -> t.Tuple[str, int]: + status = _to_str(value, self.charset) + split_status = status.split(None, 1) + + if len(split_status) == 0: + raise ValueError("Empty status argument") + + if len(split_status) > 1: + if split_status[0].isdigit(): + # code and message + return status, int(split_status[0]) + + # multi-word message + return f"0 {status}", 0 + + if split_status[0].isdigit(): + # code only + status_code = int(split_status[0]) + + try: + status = f"{status_code} {HTTP_STATUS_CODES[status_code].upper()}" + except KeyError: + status = f"{status_code} UNKNOWN" + + return status, status_code + + # one-word message + return f"0 {status}", 0 + + @typing.overload + def get_data(self, as_text: "t.Literal[False]" = False) -> bytes: + ... + + @typing.overload + def get_data(self, as_text: "t.Literal[True]") -> str: + ... + + def get_data(self, as_text=False): + """The string representation of the response body. Whenever you call + this property the response iterable is encoded and flattened. This + can lead to unwanted behavior if you stream big data. + + This behavior can be disabled by setting + :attr:`implicit_sequence_conversion` to `False`. + + If `as_text` is set to `True` the return value will be a decoded + string. + + .. versionadded:: 0.9 + """ + self._ensure_sequence() + rv = b"".join(self.iter_encoded()) + if as_text: + rv = rv.decode(self.charset) + return rv + + def set_data(self, value: t.Union[bytes, str]) -> None: + """Sets a new string as response. The value must be a string or + bytes. If a string is set it's encoded to the charset of the + response (utf-8 by default). + + .. versionadded:: 0.9 + """ + # if a string is set, it's encoded directly so that we + # can set the content length + if isinstance(value, str): + value = value.encode(self.charset) + else: + value = bytes(value) + self.response = [value] + if self.automatically_set_content_length: + self.headers["Content-Length"] = str(len(value)) + + data = property( + get_data, + set_data, + doc="A descriptor that calls :meth:`get_data` and :meth:`set_data`.", + ) + + def calculate_content_length(self) -> t.Optional[int]: + """Returns the content length if available or `None` otherwise.""" + try: + self._ensure_sequence() + except RuntimeError: + return None + return sum(len(x) for x in self.iter_encoded()) + + def _ensure_sequence(self, mutable: bool = False) -> None: + """This method can be called by methods that need a sequence. If + `mutable` is true, it will also ensure that the response sequence + is a standard Python list. + + .. versionadded:: 0.6 + """ + if self.is_sequence: + # if we need a mutable object, we ensure it's a list. + if mutable and not isinstance(self.response, list): + self.response = list(self.response) # type: ignore + return + if self.direct_passthrough: + raise RuntimeError( + "Attempted implicit sequence conversion but the" + " response object is in direct passthrough mode." + ) + if not self.implicit_sequence_conversion: + raise RuntimeError( + "The response object required the iterable to be a" + " sequence, but the implicit conversion was disabled." + " Call make_sequence() yourself." + ) + self.make_sequence() + + def make_sequence(self) -> None: + """Converts the response iterator in a list. By default this happens + automatically if required. If `implicit_sequence_conversion` is + disabled, this method is not automatically called and some properties + might raise exceptions. This also encodes all the items. + + .. versionadded:: 0.6 + """ + if not self.is_sequence: + # if we consume an iterable we have to ensure that the close + # method of the iterable is called if available when we tear + # down the response + close = getattr(self.response, "close", None) + self.response = list(self.iter_encoded()) + if close is not None: + self.call_on_close(close) + + def iter_encoded(self) -> t.Iterator[bytes]: + """Iter the response encoded with the encoding of the response. + If the response object is invoked as WSGI application the return + value of this method is used as application iterator unless + :attr:`direct_passthrough` was activated. + """ + if __debug__: + _warn_if_string(self.response) + # Encode in a separate function so that self.response is fetched + # early. This allows us to wrap the response with the return + # value from get_app_iter or iter_encoded. + return _iter_encoded(self.response, self.charset) + + def set_cookie( + self, + key: str, + value: str = "", + max_age: t.Optional[t.Union[timedelta, int]] = None, + expires: t.Optional[t.Union[str, datetime, int, float]] = None, + path: t.Optional[str] = "/", + domain: t.Optional[str] = None, + secure: bool = False, + httponly: bool = False, + samesite: t.Optional[str] = None, + ) -> None: + """Sets a cookie. + + A warning is raised if the size of the cookie header exceeds + :attr:`max_cookie_size`, but the header will still be set. + + :param key: the key (name) of the cookie to be set. + :param value: the value of the cookie. + :param max_age: should be a number of seconds, or `None` (default) if + the cookie should last only as long as the client's + browser session. + :param expires: should be a `datetime` object or UNIX timestamp. + :param path: limits the cookie to a given path, per default it will + span the whole domain. + :param domain: if you want to set a cross-domain cookie. For example, + ``domain=".example.com"`` will set a cookie that is + readable by the domain ``www.example.com``, + ``foo.example.com`` etc. Otherwise, a cookie will only + be readable by the domain that set it. + :param secure: If ``True``, the cookie will only be available + via HTTPS. + :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". + """ + self.headers.add( + "Set-Cookie", + dump_cookie( + key, + value=value, + max_age=max_age, + expires=expires, + path=path, + domain=domain, + secure=secure, + httponly=httponly, + charset=self.charset, + max_size=self.max_cookie_size, + samesite=samesite, + ), + ) + + def delete_cookie( + self, + key: str, + path: str = "/", + domain: t.Optional[str] = None, + secure: bool = False, + httponly: bool = False, + samesite: t.Optional[str] = None, + ): + """Delete a cookie. Fails silently if key doesn't exist. + + :param key: the key (name) of the cookie to be deleted. + :param path: if the cookie that should be deleted was limited to a + path, the path has to be defined here. + :param domain: if the cookie that should be deleted was limited to a + domain, that domain has to be defined here. + :param secure: If ``True``, the cookie will only be available + via HTTPS. + :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". + """ + self.set_cookie( + key, + expires=0, + max_age=0, + path=path, + domain=domain, + secure=secure, + httponly=httponly, + samesite=samesite, + ) + + @property + def is_streamed(self) -> bool: + """If the response is streamed (the response is not an iterable with + a length information) this property is `True`. In this case streamed + means that there is no information about the number of iterations. + This is usually `True` if a generator is passed to the response object. + + This is useful for checking before applying some sort of post + filtering that should not take place for streamed responses. + """ + try: + len(self.response) # type: ignore + except (TypeError, AttributeError): + return True + return False + + @property + def is_sequence(self) -> bool: + """If the iterator is buffered, this property will be `True`. A + response object will consider an iterator to be buffered if the + response attribute is a list or tuple. + + .. versionadded:: 0.6 + """ + return isinstance(self.response, (tuple, list)) + + def close(self) -> None: + """Close the wrapped response if possible. You can also use the object + in a with statement which will automatically close it. + + .. versionadded:: 0.9 + Can now be used in a with statement. + """ + if hasattr(self.response, "close"): + self.response.close() # type: ignore + for func in self._on_close: + func() + + def __enter__(self) -> "Response": + return self + + def __exit__(self, exc_type, exc_value, tb): + self.close() + + def freeze(self, no_etag: None = None) -> None: + """Make the response object ready to be pickled. Does the + following: + + * Buffer the response into a list, ignoring + :attr:`implicity_sequence_conversion` and + :attr:`direct_passthrough`. + * Set the ``Content-Length`` header. + * Generate an ``ETag`` header if one is not already set. + """ + # Always freeze the encoded response body, ignore + # implicit_sequence_conversion and direct_passthrough. + self.response = list(self.iter_encoded()) + self.headers["Content-Length"] = str(sum(map(len, self.response))) + + if no_etag is not None: + warnings.warn( + "The 'no_etag' parameter is deprecated and will be" + " removed in Werkzeug version 2.1.", + DeprecationWarning, + stacklevel=2, + ) + + self.add_etag() + + def get_wsgi_headers(self, environ: "WSGIEnvironment") -> Headers: + """This is automatically called right before the response is started + and returns headers modified for the given environment. It returns a + copy of the headers from the response with some modifications applied + if necessary. + + For example the location header (if present) is joined with the root + URL of the environment. Also the content length is automatically set + to zero here for certain status codes. + + .. versionchanged:: 0.6 + Previously that function was called `fix_headers` and modified + the response object in place. Also since 0.6, IRIs in location + and content-location headers are handled properly. + + Also starting with 0.6, Werkzeug will attempt to set the content + length if it is able to figure it out on its own. This is the + case if all the strings in the response iterable are already + encoded and the iterable is buffered. + + :param environ: the WSGI environment of the request. + :return: returns a new :class:`~werkzeug.datastructures.Headers` + object. + """ + headers = Headers(self.headers) + location: t.Optional[str] = None + content_location: t.Optional[str] = None + content_length: t.Optional[t.Union[str, int]] = None + status = self.status_code + + # iterate over the headers to find all values in one go. Because + # get_wsgi_headers is used each response that gives us a tiny + # speedup. + for key, value in headers: + ikey = key.lower() + if ikey == "location": + location = value + elif ikey == "content-location": + content_location = value + elif ikey == "content-length": + content_length = value + + # make sure the location header is an absolute URL + if location is not None: + old_location = location + if isinstance(location, str): + # Safe conversion is necessary here as we might redirect + # to a broken URI scheme (for instance itms-services). + location = iri_to_uri(location, safe_conversion=True) + + if self.autocorrect_location_header: + current_url = get_current_url(environ, strip_querystring=True) + if isinstance(current_url, str): + current_url = iri_to_uri(current_url) + location = url_join(current_url, location) + if location != old_location: + headers["Location"] = location # type: ignore + + # make sure the content location is a URL + if content_location is not None and isinstance(content_location, str): + headers["Content-Location"] = iri_to_uri(content_location) + + if 100 <= status < 200 or status == 204: + # Per section 3.3.2 of RFC 7230, "a server MUST NOT send a + # Content-Length header field in any response with a status + # code of 1xx (Informational) or 204 (No Content)." + headers.remove("Content-Length") + elif status == 304: + remove_entity_headers(headers) + + # if we can determine the content length automatically, we + # should try to do that. But only if this does not involve + # flattening the iterator or encoding of strings in the + # response. We however should not do that if we have a 304 + # response. + if ( + self.automatically_set_content_length + and self.is_sequence + and content_length is None + and status not in (204, 304) + and not (100 <= status < 200) + ): + try: + content_length = sum(len(_to_bytes(x, "ascii")) for x in self.response) + except UnicodeError: + # Something other than bytes, can't safely figure out + # the length of the response. + pass + else: + headers["Content-Length"] = str(content_length) + + return headers + + def get_app_iter(self, environ: "WSGIEnvironment") -> t.Iterable[bytes]: + """Returns the application iterator for the given environ. Depending + on the request method and the current status code the return value + might be an empty response rather than the one from the response. + + If the request method is `HEAD` or the status code is in a range + where the HTTP specification requires an empty response, an empty + iterable is returned. + + .. versionadded:: 0.6 + + :param environ: the WSGI environment of the request. + :return: a response iterable. + """ + status = self.status_code + if ( + environ["REQUEST_METHOD"] == "HEAD" + or 100 <= status < 200 + or status in (204, 304) + ): + iterable: t.Iterable[bytes] = () + elif self.direct_passthrough: + if __debug__: + _warn_if_string(self.response) + return self.response # type: ignore + else: + iterable = self.iter_encoded() + return ClosingIterator(iterable, self.close) + + def get_wsgi_response( + self, environ: "WSGIEnvironment" + ) -> t.Tuple[t.Iterable[bytes], str, t.List[t.Tuple[str, str]]]: + """Returns the final WSGI response as tuple. The first item in + the tuple is the application iterator, the second the status and + the third the list of headers. The response returned is created + specially for the given environment. For example if the request + method in the WSGI environment is ``'HEAD'`` the response will + be empty and only the headers and status code will be present. + + .. versionadded:: 0.6 + + :param environ: the WSGI environment of the request. + :return: an ``(app_iter, status, headers)`` tuple. + """ + headers = self.get_wsgi_headers(environ) + app_iter = self.get_app_iter(environ) + return app_iter, self.status, headers.to_wsgi_list() + + def __call__( + self, environ: "WSGIEnvironment", start_response: "StartResponse" + ) -> t.Iterable[bytes]: + """Process this response as WSGI application. + + :param environ: the WSGI environment. + :param start_response: the response callable provided by the WSGI + server. + :return: an application iterator + """ + app_iter, status, headers = self.get_wsgi_response(environ) + start_response(status, headers) + return app_iter + + # JSON + + #: A module or other object that has ``dumps`` and ``loads`` + #: functions that match the API of the built-in :mod:`json` module. + json_module = json + + @property + def json(self) -> t.Optional[t.Any]: + """The parsed JSON data if :attr:`mimetype` indicates JSON + (:mimetype:`application/json`, see :meth:`is_json`). + + Calls :meth:`get_json` with default arguments. + """ + return self.get_json() + + @property + def is_json(self) -> bool: + """Check if the mimetype indicates JSON data, either + :mimetype:`application/json` or :mimetype:`application/*+json`. + """ + mt = self.mimetype + return mt is not None and ( + mt == "application/json" + or mt.startswith("application/") + and mt.endswith("+json") + ) + + def get_json(self, force: bool = False, silent: bool = False) -> t.Optional[t.Any]: + """Parse :attr:`data` as JSON. Useful during testing. + + If the mimetype does not indicate JSON + (:mimetype:`application/json`, see :meth:`is_json`), this + returns ``None``. + + Unlike :meth:`Request.get_json`, the result is not cached. + + :param force: Ignore the mimetype and always try to parse JSON. + :param silent: Silence parsing errors and return ``None`` + instead. + """ + if not (force or self.is_json): + return None + + data = self.get_data() + + try: + return self.json_module.loads(data) + except ValueError: + if not silent: + raise + + return None + + # Stream + + @cached_property + def stream(self) -> "ResponseStream": + """The response iterable as write-only stream.""" + return ResponseStream(self) + + # Common Descriptors + + @property + def mimetype(self) -> t.Optional[str]: + """The mimetype (content type without charset etc.)""" + ct = self.headers.get("content-type") + + if ct: + return ct.split(";")[0].strip() + else: + return None + + @mimetype.setter + def mimetype(self, value: str) -> None: + self.headers["Content-Type"] = get_content_type(value, self.charset) + + @property + def mimetype_params(self) -> t.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'}``. + + .. versionadded:: 0.5 + """ + + def on_update(d): + self.headers["Content-Type"] = dump_options_header(self.mimetype, d) + + d = parse_options_header(self.headers.get("content-type", ""))[1] + return CallbackDict(d, on_update) + + location = header_property[str]( + "Location", + doc="""The Location response-header field is used to redirect + the recipient to a location other than the Request-URI for + completion of the request or identification of a new + resource.""", + ) + age = header_property( + "Age", + None, + parse_age, + dump_age, # type: ignore + doc="""The Age response-header field conveys the sender's + estimate of the amount of time since the response (or its + revalidation) was generated at the origin server. + + Age values are non-negative decimal integers, representing time + in seconds.""", + ) + content_type = header_property[str]( + "Content-Type", + doc="""The Content-Type entity-header field indicates the media + type of the entity-body sent to the recipient or, in the case of + the HEAD method, the media type that would have been sent had + the request been a GET.""", + ) + content_length = header_property( + "Content-Length", + None, + int, + str, + doc="""The Content-Length entity-header field indicates the size + of the entity-body, in decimal number of OCTETs, sent to the + recipient or, in the case of the HEAD method, the size of the + entity-body that would have been sent had the request been a + GET.""", + ) + content_location = header_property[str]( + "Content-Location", + doc="""The Content-Location entity-header field MAY be used to + supply the resource location for the entity enclosed in the + message when that entity is accessible from a location separate + from the requested resource's URI.""", + ) + content_encoding = header_property[str]( + "Content-Encoding", + doc="""The Content-Encoding entity-header field is used as a + modifier to the media-type. When present, its value indicates + what additional content codings have been applied to the + entity-body, and thus what decoding mechanisms must be applied + in order to obtain the media-type referenced by the Content-Type + header field.""", + ) + content_md5 = header_property[str]( + "Content-MD5", + doc="""The Content-MD5 entity-header field, as defined in + RFC 1864, is an MD5 digest of the entity-body for the purpose of + providing an end-to-end message integrity check (MIC) of the + entity-body. (Note: a MIC is good for detecting accidental + modification of the entity-body in transit, but is not proof + against malicious attacks.)""", + ) + date = header_property( + "Date", + None, + parse_date, + http_date, + doc="""The Date general-header field represents the date and + time at which the message was originated, having the same + semantics as orig-date in RFC 822.""", + ) + expires = header_property( + "Expires", + None, + parse_date, + http_date, + doc="""The Expires entity-header field gives the date/time after + which the response is considered stale. A stale cache entry may + not normally be returned by a cache.""", + ) + last_modified = header_property( + "Last-Modified", + None, + parse_date, + http_date, + doc="""The Last-Modified entity-header field indicates the date + and time at which the origin server believes the variant was + last modified.""", + ) + + @property + def retry_after(self) -> t.Optional[datetime]: + """The Retry-After response-header field can be used with a + 503 (Service Unavailable) response to indicate how long the + service is expected to be unavailable to the requesting client. + + Time in seconds until expiration or date. + """ + value = self.headers.get("retry-after") + if value is None: + return None + elif value.isdigit(): + return datetime.utcnow() + timedelta(seconds=int(value)) + return parse_date(value) + + @retry_after.setter + def retry_after(self, value: t.Optional[t.Union[datetime, int, str]]) -> None: + if value is None: + if "retry-after" in self.headers: + del self.headers["retry-after"] + return + elif isinstance(value, datetime): + value = http_date(value) + else: + value = str(value) + self.headers["Retry-After"] = value + + vary = _set_property( + "Vary", + doc="""The Vary field value indicates the set of request-header + fields that fully determines, while the response is fresh, + whether a cache is permitted to use the response to reply to a + subsequent request without revalidation.""", + ) + content_language = _set_property( + "Content-Language", + doc="""The Content-Language entity-header field describes the + natural language(s) of the intended audience for the enclosed + entity. Note that this might not be equivalent to all the + languages used within the entity-body.""", + ) + allow = _set_property( + "Allow", + doc="""The Allow entity-header field lists the set of methods + supported by the resource identified by the Request-URI. The + purpose of this field is strictly to inform the recipient of + valid methods associated with the resource. An Allow header + field MUST be present in a 405 (Method Not Allowed) + response.""", + ) + + # ETag + + @property + def cache_control(self) -> ResponseCacheControl: + """The Cache-Control general-header field is used to specify + directives that MUST be obeyed by all caching mechanisms along the + request/response chain. + """ + + def on_update(cache_control): + if not cache_control and "cache-control" in self.headers: + del self.headers["cache-control"] + elif cache_control: + self.headers["Cache-Control"] = cache_control.to_header() + + return parse_cache_control_header( + self.headers.get("cache-control"), on_update, ResponseCacheControl + ) + + def _wrap_range_response(self, start: int, length: int) -> None: + """Wrap existing Response in case of Range Request context.""" + if self.status_code == 206: + self.response = _RangeWrapper(self.response, start, length) # type: ignore + + def _is_range_request_processable(self, environ: "WSGIEnvironment") -> bool: + """Return ``True`` if `Range` header is present and if underlying + resource is considered unchanged when compared with `If-Range` header. + """ + return ( + "HTTP_IF_RANGE" not in environ + or not is_resource_modified( + environ, + self.headers.get("etag"), + None, + self.headers.get("last-modified"), + ignore_if_range=False, + ) + ) and "HTTP_RANGE" in environ + + def _process_range_request( + self, + environ: "WSGIEnvironment", + complete_length: t.Optional[int] = None, + accept_ranges: t.Optional[t.Union[bool, str]] = None, + ) -> bool: + """Handle Range Request related headers (RFC7233). If `Accept-Ranges` + header is valid, and Range Request is processable, we set the headers + as described by the RFC, and wrap the underlying response in a + RangeWrapper. + + Returns ``True`` if Range Request can be fulfilled, ``False`` otherwise. + + :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable` + if `Range` header could not be parsed or satisfied. + """ + from ..exceptions import RequestedRangeNotSatisfiable + + if ( + accept_ranges is None + or complete_length is None + or not self._is_range_request_processable(environ) + ): + return False + + parsed_range = parse_range_header(environ.get("HTTP_RANGE")) + + if parsed_range is None: + raise RequestedRangeNotSatisfiable(complete_length) + + range_tuple = parsed_range.range_for_length(complete_length) + content_range_header = parsed_range.to_content_range_header(complete_length) + + if range_tuple is None or content_range_header is None: + raise RequestedRangeNotSatisfiable(complete_length) + + content_length = range_tuple[1] - range_tuple[0] + self.headers["Content-Length"] = content_length + self.headers["Accept-Ranges"] = accept_ranges + self.content_range = content_range_header # type: ignore + self.status_code = 206 + self._wrap_range_response(range_tuple[0], content_length) + return True + + def make_conditional( + self, + request_or_environ: "WSGIEnvironment", + accept_ranges: t.Union[bool, str] = False, + complete_length: t.Optional[int] = None, + ): + """Make the response conditional to the request. This method works + best if an etag was defined for the response already. The `add_etag` + method can be used to do that. If called without etag just the date + header is set. + + This does nothing if the request method in the request or environ is + anything but GET or HEAD. + + For optimal performance when handling range requests, it's recommended + that your response data object implements `seekable`, `seek` and `tell` + methods as described by :py:class:`io.IOBase`. Objects returned by + :meth:`~werkzeug.wsgi.wrap_file` automatically implement those methods. + + It does not remove the body of the response because that's something + the :meth:`__call__` function does for us automatically. + + Returns self so that you can do ``return resp.make_conditional(req)`` + but modifies the object in-place. + + :param request_or_environ: a request object or WSGI environment to be + used to make the response conditional + against. + :param accept_ranges: This parameter dictates the value of + `Accept-Ranges` header. If ``False`` (default), + the header is not set. If ``True``, it will be set + to ``"bytes"``. If ``None``, it will be set to + ``"none"``. If it's a string, it will use this + value. + :param complete_length: Will be used only in valid Range Requests. + It will set `Content-Range` complete length + value and compute `Content-Length` real value. + This parameter is mandatory for successful + Range Requests completion. + :raises: :class:`~werkzeug.exceptions.RequestedRangeNotSatisfiable` + if `Range` header could not be parsed or satisfied. + """ + environ = _get_environ(request_or_environ) + if environ["REQUEST_METHOD"] in ("GET", "HEAD"): + # if the date is not in the headers, add it now. We however + # will not override an already existing header. Unfortunately + # this header will be overriden by many WSGI servers including + # wsgiref. + if "date" not in self.headers: + self.headers["Date"] = http_date() + accept_ranges = _clean_accept_ranges(accept_ranges) + is206 = self._process_range_request(environ, complete_length, accept_ranges) + if not is206 and not is_resource_modified( + environ, + self.headers.get("etag"), + None, + self.headers.get("last-modified"), + ): + if parse_etags(environ.get("HTTP_IF_MATCH")): + self.status_code = 412 + else: + self.status_code = 304 + if ( + self.automatically_set_content_length + and "content-length" not in self.headers + ): + length = self.calculate_content_length() + if length is not None: + self.headers["Content-Length"] = length + return self + + def add_etag(self, overwrite: bool = False, weak: bool = False) -> None: + """Add an etag for the current response if there is none yet.""" + if overwrite or "etag" not in self.headers: + self.set_etag(generate_etag(self.get_data()), weak) + + def set_etag(self, etag: str, weak: bool = False) -> None: + """Set the etag, and override the old one if there was one.""" + self.headers["ETag"] = quote_etag(etag, weak) + + def get_etag(self) -> t.Union[t.Tuple[str, bool], t.Tuple[None, None]]: + """Return a tuple in the form ``(etag, is_weak)``. If there is no + ETag the return value is ``(None, None)``. + """ + return unquote_etag(self.headers.get("ETag")) + + accept_ranges = header_property[str]( + "Accept-Ranges", + doc="""The `Accept-Ranges` header. Even though the name would + indicate that multiple values are supported, it must be one + string token only. + + The values ``'bytes'`` and ``'none'`` are common. + + .. versionadded:: 0.7""", + ) + + @property + def content_range(self) -> ContentRange: + """The ``Content-Range`` header as a + :class:`~werkzeug.datastructures.ContentRange` object. Available + even if the header is not set. + + .. versionadded:: 0.7 + """ + + def on_update(rng: ContentRange) -> None: + if not rng: + del self.headers["content-range"] + else: + self.headers["Content-Range"] = rng.to_header() + + rv = parse_content_range_header(self.headers.get("content-range"), on_update) + # always provide a content range object to make the descriptor + # more user friendly. It provides an unset() method that can be + # used to remove the header quickly. + if rv is None: + rv = ContentRange(None, None, None, on_update=on_update) + return rv + + @content_range.setter + def content_range(self, value: t.Optional[t.Union[ContentRange, str]]) -> None: + if not value: + del self.headers["content-range"] + elif isinstance(value, str): + self.headers["Content-Range"] = value + else: + self.headers["Content-Range"] = value.to_header() + + # Authorization + + @property + def www_authenticate(self) -> WWWAuthenticate: + """The ``WWW-Authenticate`` header in a parsed form.""" + + def on_update(www_auth: WWWAuthenticate) -> None: + if not www_auth and "www-authenticate" in self.headers: + del self.headers["www-authenticate"] + elif www_auth: + self.headers["WWW-Authenticate"] = www_auth.to_header() + + header = self.headers.get("www-authenticate") + return parse_www_authenticate_header(header, on_update) + + # CSP + + content_security_policy = header_property( + "Content-Security-Policy", + None, + parse_csp_header, # type: ignore + dump_csp_header, + doc="""The Content-Security-Policy header adds an additional layer of + security to help detect and mitigate certain types of attacks.""", + ) + content_security_policy_report_only = header_property( + "Content-Security-Policy-Report-Only", + None, + parse_csp_header, # type: ignore + dump_csp_header, + doc="""The Content-Security-Policy-Report-Only header adds a csp policy + that is not enforced but is reported thereby helping detect + certain types of attacks.""", + ) + + # CORS + + @property + def access_control_allow_credentials(self) -> bool: + """Whether credentials can be shared by the browser to + JavaScript code. As part of the preflight request it indicates + whether credentials can be used on the cross origin request. + """ + return "Access-Control-Allow-Credentials" in self.headers + + @access_control_allow_credentials.setter + def access_control_allow_credentials(self, value: t.Optional[bool]) -> None: + if value is True: + self.headers["Access-Control-Allow-Credentials"] = "true" + else: + self.headers.pop("Access-Control-Allow-Credentials", None) + + access_control_allow_headers = header_property( + "Access-Control-Allow-Headers", + load_func=parse_set_header, + dump_func=dump_header, + doc="Which headers can be sent with the cross origin request.", + ) + + access_control_allow_methods = header_property( + "Access-Control-Allow-Methods", + load_func=parse_set_header, + dump_func=dump_header, + doc="Which methods can be used for the cross origin request.", + ) + + access_control_allow_origin = header_property[str]( + "Access-Control-Allow-Origin", + doc="The origin or '*' for any origin that may make cross origin requests.", + ) + + access_control_expose_headers = header_property( + "Access-Control-Expose-Headers", + load_func=parse_set_header, + dump_func=dump_header, + doc="Which headers can be shared by the browser to JavaScript code.", + ) + + access_control_max_age = header_property( + "Access-Control-Max-Age", + load_func=int, + dump_func=str, + doc="The maximum age in seconds the access control settings can be cached for.", + ) class ResponseStream: @@ -14,9 +1371,9 @@ class ResponseStream: iterable of the response object. """ - mode: str = "wb+" + mode = "wb+" - def __init__(self, response: BaseResponse): + def __init__(self, response: Response): self.response = response self.closed = False @@ -54,33 +1411,12 @@ class ResponseStream: class ResponseStreamMixin: - """Mixin for :class:`BaseResponse` subclasses. Classes that inherit from - this mixin will automatically get a :attr:`stream` property that provides - a write-only interface to the response iterable. - """ - - @cached_property - def stream(self) -> ResponseStream: - """The response iterable as write-only stream.""" - return ResponseStream(self) # type: ignore - - -class Response( # type: ignore - BaseResponse, - ETagResponseMixin, - WWWAuthenticateMixin, - CORSResponseMixin, - ResponseStreamMixin, - CommonResponseDescriptorsMixin, -): - """Full featured response object implementing the following mixins: - - - :class:`ETagResponseMixin` for etag and cache control handling - - :class:`WWWAuthenticateMixin` for HTTP authentication support - - :class:`~werkzeug.wrappers.cors.CORSResponseMixin` for Cross - Origin Resource Sharing headers - - :class:`ResponseStreamMixin` to add support for the ``stream`` - property - - :class:`CommonResponseDescriptorsMixin` for various HTTP - descriptors - """ + def __init__(self, *args, **kwargs): + warnings.warn( + "'ResponseStreamMixin' is deprecated and will be removed in" + " Werkzeug version 2.1. 'Response' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wrappers/user_agent.py b/src/werkzeug/wrappers/user_agent.py index a402d426..5759e3dc 100644 --- a/src/werkzeug/wrappers/user_agent.py +++ b/src/werkzeug/wrappers/user_agent.py @@ -1,17 +1,13 @@ -from ..datastructures import EnvironHeaders -from ..useragents import UserAgent -from ..utils import cached_property +import warnings class UserAgentMixin: - """Adds a `user_agent` attribute to the request object which - contains the parsed user agent of the browser that triggered the - request as a :class:`~werkzeug.useragents.UserAgent` object. - """ - - headers: EnvironHeaders - - @cached_property - def user_agent(self) -> UserAgent: - """The current user agent.""" - return UserAgent(self.headers.get("User-Agent", "")) # type: ignore + def __init__(self, *args, **kwargs): + warnings.warn( + "'UserAgentMixin' is deprecated and will be removed in" + " Werkzeug version 2.1. 'Request' now includes the" + " functionality directly.", + DeprecationWarning, + stacklevel=2, + ) + super().__init__(*args, **kwargs) diff --git a/src/werkzeug/wsgi.py b/src/werkzeug/wsgi.py index 9a39b80f..8d18fa43 100644 --- a/src/werkzeug/wsgi.py +++ b/src/werkzeug/wsgi.py @@ -527,7 +527,7 @@ def wrap_file( If the file wrapper from the WSGI server is used it's important to not iterate over it from inside the application but to pass it through unchanged. If you want to pass out a file wrapper inside a response - object you have to set :attr:`~BaseResponse.direct_passthrough` to `True`. + object you have to set :attr:`Response.direct_passthrough` to `True`. More information about file wrappers are available in :pep:`333`. @@ -548,7 +548,7 @@ class FileWrapper: .. versionadded:: 0.5 - If you're using this object together with a :class:`BaseResponse` you have + If you're using this object together with a :class:`Response` you have to use the `direct_passthrough` mode. :param file: a :class:`file`-like object with a :meth:`~file.read` method. @@ -598,7 +598,7 @@ class _RangeWrapper: The yielded blocks will have a size that can't exceed the original iterator defined block size, but that can be smaller. - If you're using this object together with a :class:`BaseResponse` you have + If you're using this object together with a :class:`Response` you have to use the `direct_passthrough` mode. :param iterable: an iterable object with a :meth:`__next__` method. diff --git a/tests/test_test.py b/tests/test_test.py index 2cb080b1..b27b8ff2 100644 --- a/tests/test_test.py +++ b/tests/test_test.py @@ -19,7 +19,6 @@ from werkzeug.test import EnvironBuilder from werkzeug.test import run_wsgi_app from werkzeug.test import stream_encode_multipart from werkzeug.utils import redirect -from werkzeug.wrappers import BaseResponse from werkzeug.wrappers import Request from werkzeug.wrappers import Response from werkzeug.wsgi import pop_path_info @@ -422,7 +421,7 @@ def test_follow_redirect(): def test_follow_local_redirect(): - class LocalResponse(BaseResponse): + class LocalResponse(Response): autocorrect_location_header = False def local_redirect_app(environ, start_response): diff --git a/tests/test_utils.py b/tests/test_utils.py index 5c396844..65ca23a4 100644 --- a/tests/test_utils.py +++ b/tests/test_utils.py @@ -8,7 +8,7 @@ from werkzeug.datastructures import Headers from werkzeug.http import http_date from werkzeug.http import parse_date from werkzeug.test import Client -from werkzeug.wrappers import BaseResponse +from werkzeug.wrappers import Response def test_redirect(): @@ -40,7 +40,7 @@ def test_redirect_xss(): def test_redirect_with_custom_response_class(): - class MyResponse(BaseResponse): + class MyResponse(Response): pass location = "http://example.com/redirect" diff --git a/tests/test_wrappers.py b/tests/test_wrappers.py index 27d449da..682abed5 100644 --- a/tests/test_wrappers.py +++ b/tests/test_wrappers.py @@ -26,7 +26,6 @@ from werkzeug.http import generate_etag from werkzeug.test import Client from werkzeug.test import create_environ from werkzeug.test import run_wsgi_app -from werkzeug.wrappers.json import JSONMixin from werkzeug.wsgi import LimitedStream from werkzeug.wsgi import wrap_file @@ -167,7 +166,7 @@ def test_url_request_descriptors_hosts(): pytest.raises(SecurityError, lambda: req.host) -def test_authorization_mixin(): +def test_authorization(): request = wrappers.Request.from_values( headers={"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="} ) @@ -187,16 +186,6 @@ def test_authorization_with_unicode(): assert a.password == "Буквы" -def test_stream_only_mixing(): - request = wrappers.PlainRequest.from_values( - data=b"foo=blub+hehe", content_type="application/x-www-form-urlencoded" - ) - assert list(request.files.items()) == [] - assert list(request.form.items()) == [] - pytest.raises(AttributeError, lambda: request.data) - assert request.stream.read() == b"foo=blub+hehe" - - def test_request_application(): @wrappers.Request.application def application(request): @@ -241,7 +230,7 @@ def test_response_access_control(): def test_base_response(): - response = wrappers.BaseResponse("öäü") + response = wrappers.Response("öäü") assert response.get_data() == "öäü".encode() # writing @@ -250,7 +239,7 @@ def test_base_response(): assert response.get_data() == b"foobar" # set cookie - response = wrappers.BaseResponse() + response = wrappers.Response() response.set_cookie( "foo", value="bar", @@ -271,7 +260,7 @@ def test_base_response(): ] # delete cookie - response = wrappers.BaseResponse() + response = wrappers.Response() response.delete_cookie("foo") assert response.headers.to_wsgi_list() == [ ("Content-Type", "text/plain; charset=utf-8"), @@ -294,7 +283,7 @@ def test_base_response(): def close(self): closed.append(True) - response = wrappers.BaseResponse(Iterable()) + response = wrappers.Response(Iterable()) response.call_on_close(lambda: closed.append(True)) app_iter, status, headers = run_wsgi_app(response, create_environ(), buffered=True) assert status == "200 OK" @@ -303,7 +292,7 @@ def test_base_response(): # with statement del closed[:] - response = wrappers.BaseResponse(Iterable()) + response = wrappers.Response(Iterable()) with response: pass assert len(closed) == 1 @@ -319,7 +308,7 @@ def test_base_response(): ], ) def test_response_set_status_code(status_code, expected_status): - response = wrappers.BaseResponse() + response = wrappers.Response() response.status_code = status_code assert response.status_code == status_code assert response.status == expected_status @@ -340,7 +329,7 @@ def test_response_set_status_code(status_code, expected_status): ], ) def test_response_set_status(status, expected_status_code, expected_status): - response = wrappers.BaseResponse() + response = wrappers.Response() response.status = status assert response.status_code == expected_status_code assert response.status == expected_status @@ -353,14 +342,14 @@ def test_response_set_status(status, expected_status_code, expected_status): def test_response_init_status_empty_string(): # invalid status codes with pytest.raises(ValueError) as info: - wrappers.BaseResponse(None, "") + wrappers.Response(None, "") assert "Empty status argument" in str(info.value) def test_response_init_status_tuple(): with pytest.raises(TypeError) as info: - wrappers.BaseResponse(None, tuple()) + wrappers.Response(None, tuple()) assert "Invalid status argument" in str(info.value) @@ -370,7 +359,7 @@ def test_type_forcing(): start_response("200 OK", [("Content-Type", "text/html")]) return ["Hello World!"] - base_response = wrappers.BaseResponse("Hello World!", content_type="text/html") + base_response = wrappers.Response("Hello World!", content_type="text/html") class SpecialResponse(wrappers.Response): def foo(self): @@ -391,7 +380,7 @@ def test_type_forcing(): pytest.raises(TypeError, SpecialResponse.force_type, wsgi_application) -def test_accept_mixin(): +def test_accept(): request = wrappers.Request( { "HTTP_ACCEPT": "text/xml,application/xml,application/xhtml+xml," @@ -422,7 +411,7 @@ def test_accept_mixin(): assert request.accept_mimetypes == MIMEAccept() -def test_etag_request_mixin(): +def test_etag_request(): request = wrappers.Request( { "HTTP_CACHE_CONTROL": "no-store, no-cache", @@ -445,7 +434,7 @@ def test_etag_request_mixin(): assert request.if_unmodified_since == datetime(2008, 1, 22, 11, 18, 44) -def test_user_agent_mixin(): +def test_user_agent(): user_agents = [ ( "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1.11) " @@ -704,7 +693,7 @@ def test_get_data_method_parsing_caching_behavior(): assert req.form["foo"] == "Hello World" -def test_etag_response_mixin(): +def test_etag_response(): response = wrappers.Response("Hello World") assert response.get_etag() == (None, None) response.add_etag() @@ -867,27 +856,13 @@ def test_invalid_range_request(): response.make_conditional(env, accept_ranges=True, complete_length=11) -def test_etag_response_mixin_freezing(): - class WithFreeze(wrappers.ETagResponseMixin, wrappers.BaseResponse): # type: ignore - pass - - class WithoutFreeze( # type: ignore - wrappers.BaseResponse, wrappers.ETagResponseMixin - ): - pass - - response = WithFreeze("Hello World") +def test_etag_response_freezing(): + response = Response("Hello World") response.freeze() assert response.get_etag() == (str(generate_etag(b"Hello World")), False) - response = WithoutFreeze("Hello World") - response.freeze() - assert response.get_etag() == (None, None) - response = wrappers.Response("Hello World") - response.freeze() - assert response.get_etag() == (None, None) -def test_authenticate_mixin(): +def test_authenticate(): resp = wrappers.Response() resp.www_authenticate.type = "basic" resp.www_authenticate.realm = "Testing" @@ -897,7 +872,7 @@ def test_authenticate_mixin(): assert "WWW-Authenticate" not in resp.headers -def test_authenticate_mixin_quoted_qop(): +def test_authenticate_quoted_qop(): # Example taken from https://github.com/pallets/werkzeug/issues/633 resp = wrappers.Response() resp.www_authenticate.set_digest("REALM", "NONCE", qop=("auth", "auth-int")) @@ -913,7 +888,7 @@ def test_authenticate_mixin_quoted_qop(): assert actual == expected -def test_response_stream_mixin(): +def test_response_stream(): response = wrappers.Response() response.stream.write("Hello ") response.stream.write("World!") @@ -921,7 +896,7 @@ def test_response_stream_mixin(): assert response.get_data() == b"Hello World!" -def test_common_response_descriptors_mixin(): +def test_common_response_descriptors(): response = wrappers.Response() response.mimetype = "text/html" assert response.mimetype == "text/html" @@ -969,7 +944,7 @@ def test_common_response_descriptors_mixin(): assert response.headers["Content-Language"] == "en-US, fr" -def test_common_request_descriptors_mixin(): +def test_common_request_descriptors(): request = wrappers.Request.from_values( content_type="text/html; charset=utf-8", content_length="23", @@ -1408,10 +1383,8 @@ def test_stream_zip(): class TestSetCookie: - """Tests for :meth:`werkzeug.wrappers.BaseResponse.set_cookie`.""" - def test_secure(self): - response = wrappers.BaseResponse() + response = wrappers.Response() response.set_cookie( "foo", value="bar", @@ -1433,7 +1406,7 @@ class TestSetCookie: ] def test_httponly(self): - response = wrappers.BaseResponse() + response = wrappers.Response() response.set_cookie( "foo", value="bar", @@ -1456,7 +1429,7 @@ class TestSetCookie: ] def test_secure_and_httponly(self): - response = wrappers.BaseResponse() + response = wrappers.Response() response.set_cookie( "foo", value="bar", @@ -1479,7 +1452,7 @@ class TestSetCookie: ] def test_samesite(self): - response = wrappers.BaseResponse() + response = wrappers.Response() response.set_cookie( "foo", value="bar", @@ -1501,34 +1474,28 @@ class TestSetCookie: ] -class TestJSONMixin: - class Request(JSONMixin, wrappers.Request): # type: ignore - pass - - class Response(JSONMixin, wrappers.Response): # type: ignore - pass - +class TestJSON: def test_request(self): value = {"ä": "b"} - request = self.Request.from_values(json=value) + request = wrappers.Request.from_values(json=value) assert request.json == value assert request.get_data() def test_response(self): value = {"ä": "b"} - response = self.Response( + response = wrappers.Response( response=json.dumps(value), content_type="application/json" ) assert response.json == value def test_force(self): value = [1, 2, 3] - request = self.Request.from_values(json=value, content_type="text/plain") + request = wrappers.Request.from_values(json=value, content_type="text/plain") assert request.json is None assert request.get_json(force=True) == value def test_silent(self): - request = self.Request.from_values( + request = wrappers.Request.from_values( data=b'{"a":}', content_type="application/json" ) assert request.get_json(silent=True) is None @@ -1538,7 +1505,7 @@ class TestJSONMixin: def test_cache_disabled(self): value = [1, 2, 3] - request = self.Request.from_values(json=value) + request = wrappers.Request.from_values(json=value) assert request.get_json(cache=False) == [1, 2, 3] assert not request.get_data() diff --git a/tests/test_wsgi.py b/tests/test_wsgi.py index 17180670..4bb1cae9 100644 --- a/tests/test_wsgi.py +++ b/tests/test_wsgi.py @@ -10,7 +10,7 @@ from werkzeug.exceptions import ClientDisconnected from werkzeug.test import Client from werkzeug.test import create_environ from werkzeug.test import run_wsgi_app -from werkzeug.wrappers import BaseResponse +from werkzeug.wrappers import Response from werkzeug.wsgi import _RangeWrapper from werkzeug.wsgi import ClosingIterator from werkzeug.wsgi import wrap_file @@ -73,7 +73,7 @@ def test_get_host_validate_trusted_hosts(): def test_responder(): def foo(environ, start_response): - return BaseResponse(b"Test") + return Response(b"Test") client = Client(wsgi.responder(foo)) response = client.get("/") @@ -408,26 +408,26 @@ def test_lines_longer_buffer_size_cap(): def test_range_wrapper(): - response = BaseResponse(b"Hello World") + response = Response(b"Hello World") range_wrapper = _RangeWrapper(response.response, 6, 4) assert next(range_wrapper) == b"Worl" - response = BaseResponse(b"Hello World") + response = Response(b"Hello World") range_wrapper = _RangeWrapper(response.response, 1, 0) with pytest.raises(StopIteration): next(range_wrapper) - response = BaseResponse(b"Hello World") + response = Response(b"Hello World") range_wrapper = _RangeWrapper(response.response, 6, 100) assert next(range_wrapper) == b"World" - response = BaseResponse(x for x in (b"He", b"ll", b"o ", b"Wo", b"rl", b"d")) + response = Response(x for x in (b"He", b"ll", b"o ", b"Wo", b"rl", b"d")) range_wrapper = _RangeWrapper(response.response, 6, 4) assert not range_wrapper.seekable assert next(range_wrapper) == b"Wo" assert next(range_wrapper) == b"rl" - response = BaseResponse(x for x in (b"He", b"ll", b"o W", b"o", b"rld")) + response = Response(x for x in (b"He", b"ll", b"o W", b"o", b"rld")) range_wrapper = _RangeWrapper(response.response, 6, 4) assert next(range_wrapper) == b"W" assert next(range_wrapper) == b"o" @@ -435,7 +435,7 @@ def test_range_wrapper(): with pytest.raises(StopIteration): next(range_wrapper) - response = BaseResponse(x for x in (b"Hello", b" World")) + response = Response(x for x in (b"Hello", b" World")) range_wrapper = _RangeWrapper(response.response, 1, 1) assert next(range_wrapper) == b"e" with pytest.raises(StopIteration): @@ -444,7 +444,7 @@ def test_range_wrapper(): resources = os.path.join(os.path.dirname(__file__), "res") env = create_environ() with open(os.path.join(resources, "test.txt"), "rb") as f: - response = BaseResponse(wrap_file(env, f)) + response = Response(wrap_file(env, f)) range_wrapper = _RangeWrapper(response.response, 1, 2) assert range_wrapper.seekable assert next(range_wrapper) == b"OU" @@ -452,7 +452,7 @@ def test_range_wrapper(): next(range_wrapper) with open(os.path.join(resources, "test.txt"), "rb") as f: - response = BaseResponse(wrap_file(env, f)) + response = Response(wrap_file(env, f)) range_wrapper = _RangeWrapper(response.response, 2) assert next(range_wrapper) == b"UND\n" with pytest.raises(StopIteration): |
