class documentation

Represents an outgoing WSGI 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 Werkzeug 2.1. .. versionchanged:: 0.5 The ``direct_passthrough`` parameter was added.

Class Method force_type 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.
Class Method from_app 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...
Method __call__ Process this response as WSGI application.
Method __enter__ Undocumented
Method __exit__ Undocumented
Method __init__ Undocumented
Method __repr__ Undocumented
Method add_etag Add an etag for the current response if there is none yet.
Method calculate_content_length Returns the content length if available or `None` otherwise.
Method call_on_close 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.
Method close Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.
Method freeze Make the response object ready to be pickled. Does the following:
Method get_app_iter 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.
Method get_data 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.
Method get_json Parse :attr:`data` as JSON. Useful during testing.
Method get_wsgi_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.
Method get_wsgi_response 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...
Method iter_encoded 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.
Method make_conditional 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.
Method make_sequence 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...
Method set_data 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).
Class Variable autocorrect_location_header Undocumented
Class Variable automatically_set_content_length Undocumented
Class Variable data Undocumented
Class Variable implicit_sequence_conversion Undocumented
Instance Variable content_range The ``Content-Range`` header as a :class:`~werkzeug.datastructures.ContentRange` object. Available even if the header is not set.
Instance Variable direct_passthrough Undocumented
Instance Variable response Undocumented
Instance Variable status_code The HTTP status code as a number.
Property is_sequence 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.
Property is_streamed 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...
Property json The parsed JSON data if :attr:`mimetype` indicates JSON (:mimetype:`application/json`, see :attr:`is_json`).
Property stream The response iterable as write-only stream.
Method _ensure_sequence 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.
Method _is_range_request_processable Return ``True`` if `Range` header is present and if underlying resource is considered unchanged when compared with `If-Range` header.
Method _process_range_request 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.
Method _wrap_range_response Wrap existing Response in case of Range Request context.
Instance Variable _on_close Undocumented

Inherited from Response:

Method access_control_allow_credentials.setter Undocumented
Method content_range.setter Undocumented
Method content_security_policy.setter Undocumented
Method content_security_policy_report_only.setter Undocumented
Method delete_cookie Delete a cookie. Fails silently if key doesn't exist.
Method get_etag Return a tuple in the form ``(etag, is_weak)``. If there is no ETag the return value is ``(None, None)``.
Method mimetype.setter Undocumented
Method retry_after.setter Undocumented
Method set_cookie Sets a cookie.
Method set_etag Set the etag, and override the old one if there was one.
Method status.setter Undocumented
Method status_code.setter Undocumented
Class Variable accept_ranges Undocumented
Class Variable access_control_allow_headers Undocumented
Class Variable access_control_allow_methods Undocumented
Class Variable access_control_allow_origin Undocumented
Class Variable access_control_expose_headers Undocumented
Class Variable access_control_max_age Undocumented
Class Variable age Undocumented
Class Variable allow Undocumented
Class Variable charset Undocumented
Class Variable content_encoding Undocumented
Class Variable content_language Undocumented
Class Variable content_length Undocumented
Class Variable content_location Undocumented
Class Variable content_md5 Undocumented
Class Variable content_type Undocumented
Class Variable cross_origin_embedder_policy Undocumented
Class Variable cross_origin_opener_policy Undocumented
Class Variable date Undocumented
Class Variable default_mimetype Undocumented
Class Variable default_status Undocumented
Class Variable expires Undocumented
Class Variable last_modified Undocumented
Class Variable location Undocumented
Class Variable max_cookie_size Undocumented
Class Variable vary Undocumented
Instance Variable headers Undocumented
Property access_control_allow_credentials 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.
Property cache_control The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain.
Property content_security_policy The ``Content-Security-Policy`` header as a :class:`~werkzeug.datastructures.ContentSecurityPolicy` object. Available even if the header is not set.
Property content_security_policy_report_only The ``Content-Security-policy-report-only`` header as a :class:`~werkzeug.datastructures.ContentSecurityPolicy` object. Available even if the header is not set.
Property is_json Check if the mimetype indicates JSON data, either :mimetype:`application/json` or :mimetype:`application/*+json`.
Property mimetype The mimetype (content type without charset etc.)
Property mimetype_params The mimetype parameters as dict. For example if the content type is ``text/html; charset=utf-8`` the params would be ``{'charset': 'utf-8'}``.
Property retry_after 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.
Property status The HTTP status code as a string.
Property www_authenticate The ``WWW-Authenticate`` header in a parsed form.
Method _clean_status Undocumented
Instance Variable _status Undocumented
Instance Variable _status_code Undocumented
@classmethod
def force_type(cls, response: Response, environ: t.Optional[WSGIEnvironment] = None) -> Response: (source)

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.

@classmethod
def from_app(cls, app: WSGIApplication, environ: WSGIEnvironment, buffered: bool = False) -> Response: (source)

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.

def __call__(self, environ: WSGIEnvironment, start_response: StartResponse) -> t.Iterable[bytes]: (source)

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

def __enter__(self) -> Response: (source)

Undocumented

def __exit__(self, exc_type, exc_value, tb): (source)

Undocumented

def __repr__(self) -> str: (source)
def add_etag(self, overwrite: bool = False, weak: bool = False): (source)

Add an etag for the current response if there is none yet. .. versionchanged:: 2.0 SHA-1 is used to generate the value. MD5 may not be available in some environments.

def calculate_content_length(self) -> t.Optional[int]: (source)

Returns the content length if available or `None` otherwise.

def call_on_close(self, func: t.Callable[[], t.Any]) -> t.Callable[[], t.Any]: (source)

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

def close(self): (source)

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.

def freeze(self): (source)

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. .. versionchanged:: 2.1 Removed the ``no_etag`` parameter. .. versionchanged:: 2.0 An ``ETag`` header is added, the ``no_etag`` parameter is deprecated and will be removed in Werkzeug 2.1. .. versionchanged:: 0.6 The ``Content-Length`` header is set.

def get_app_iter(self, environ: WSGIEnvironment) -> t.Iterable[bytes]: (source)

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.

@typing.overload
def get_data(self, as_text: te.Literal[False] = False) -> bytes:
@typing.overload
def get_data(self, as_text: te.Literal[True]) -> str:
(source)

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

@t.overload
def get_json(self, force: bool = ..., silent: te.Literal[False] = ...) -> t.Any:
@t.overload
def get_json(self, force: bool = ..., silent: bool = ...) -> t.Optional[t.Any]:
(source)

Parse :attr:`data` as JSON. Useful during testing. If the mimetype does not indicate JSON (:mimetype:`application/json`, see :attr:`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.

def get_wsgi_headers(self, environ: WSGIEnvironment) -> Headers: (source)

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.

def get_wsgi_response(self, environ: WSGIEnvironment) -> t.Tuple[t.Iterable[bytes], str, t.List[t.Tuple[str, str]]]: (source)

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.

def iter_encoded(self) -> t.Iterator[bytes]: (source)

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.

def make_conditional(self, request_or_environ: t.Union[WSGIEnvironment, Request], accept_ranges: t.Union[bool, str] = False, complete_length: t.Optional[int] = None) -> Response: (source)

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. .. versionchanged:: 2.0 Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error.

def make_sequence(self): (source)

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

def set_data(self, value: t.Union[bytes, str]): (source)

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

autocorrect_location_header: bool = (source)

Undocumented

automatically_set_content_length: bool = (source)

Undocumented

Undocumented

implicit_sequence_conversion: bool = (source)

Undocumented

content_range = (source)

The ``Content-Range`` header as a :class:`~werkzeug.datastructures.ContentRange` object. Available even if the header is not set. .. versionadded:: 0.7

direct_passthrough = (source)

Undocumented

response = (source)

Undocumented

status_code: int = (source)

The HTTP status code as a number.

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

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.

The parsed JSON data if :attr:`mimetype` indicates JSON (:mimetype:`application/json`, see :attr:`is_json`). Calls :meth:`get_json` with default arguments.

The response iterable as write-only stream.

def _ensure_sequence(self, mutable: bool = False): (source)

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

def _is_range_request_processable(self, environ: WSGIEnvironment) -> bool: (source)

Return ``True`` if `Range` header is present and if underlying resource is considered unchanged when compared with `If-Range` header.

def _process_range_request(self, environ: WSGIEnvironment, complete_length: t.Optional[int] = None, accept_ranges: t.Optional[t.Union[bool, str]] = None) -> bool: (source)

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. .. versionchanged:: 2.0 Returns ``False`` if the length is 0.

def _wrap_range_response(self, start: int, length: int): (source)

Wrap existing Response in case of Range Request context.

Undocumented