Request / Response Objects

The request and response objects wrap the WSGI environment or the return value from a WSGI application so that it is another WSGI application (wraps a whole application).

How they Work

Your WSGI application is always passed two arguments. The WSGI “environment” and the WSGI start_response function that is used to start the response phase. The Request class wraps the environ for easier access to request variables (form data, request headers etc.).

The Response on the other hand is a standard WSGI application that you can create. The simple hello world in Werkzeug looks like this:

from werkzeug.wrappers import Response
application = Response('Hello World!')

To make it more useful you can replace it with a function and do some processing:

from werkzeug.wrappers import Request, Response

def application(environ, start_response):
    request = Request(environ)
    response = Response(f"Hello {request.args.get('name', 'World!')}!")
    return response(environ, start_response)

Because this is a very common task the Request object provides a helper for that. The above code can be rewritten like this:

from werkzeug.wrappers import Request, Response

@Request.application
def application(request):
    return Response(f"Hello {request.args.get('name', 'World!')}!")

The application is still a valid WSGI application that accepts the environment and start_response callable.

Mutability and Reusability of Wrappers

The implementation of the Werkzeug request and response objects are trying to guard you from common pitfalls by disallowing certain things as much as possible. This serves two purposes: high performance and avoiding of pitfalls.

For the request object the following rules apply:

  1. The request object is immutable. Modifications are not supported by default, you may however replace the immutable attributes with mutable attributes if you need to modify it.

  2. The request object may be shared in the same thread, but is not thread safe itself. If you need to access it from multiple threads, use locks around calls.

  3. It’s not possible to pickle the request object.

For the response object the following rules apply:

  1. The response object is mutable

  2. The response object can be pickled or copied after freeze() was called.

  3. Since Werkzeug 0.6 it’s safe to use the same response object for multiple WSGI responses.

  4. It’s possible to create copies using copy.deepcopy.

Wrapper Classes

class werkzeug.wrappers.Request(environ, populate_request=True, shallow=False)

Represents an incoming WSGI 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 charset.

Parameters:
  • environ (WSGIEnvironment) – The WSGI environ is generated by the WSGI server and contains information about the server configuration and client request.

  • populate_request (bool) – Add this request object to the WSGI environ as environ['werkzeug.request']. Can be useful when debugging.

  • shallow (bool) – Makes reading from stream (and any method that would read from it) raise a RuntimeError. Useful to prevent consuming the form data in middleware, which would make it unavailable to the final application.

Changed in version 3.0: The charset, url_charset, and encoding_errors parameters were removed.

Changelog

Changed in version 2.1: Old BaseRequest and mixin classes were removed.

Changed in version 2.1: Remove the disable_data_descriptor attribute.

Changed in version 2.0: Combine BaseRequest and mixins into a single Request class.

Changed in version 0.5: Read-only mode is enforced with immutable classes for all data.

_get_file_stream(total_content_length, content_type, filename=None, content_length=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.

Parameters:
  • total_content_length (int | None) – the total content length of all the data in the request combined. This value is guaranteed to be there.

  • content_type (str | None) – the mimetype of the uploaded file.

  • filename (str | None) – the filename of the uploaded file. May be None.

  • content_length (int | None) – the length of this file. This value is usually not provided because webbrowsers do not provide this value.

Return type:

IO[bytes]

property accept_charsets: CharsetAccept

List of charsets this client supports as CharsetAccept object.

property accept_encodings: Accept

List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at accept_charset.

property accept_languages: LanguageAccept

List of languages this client accepts as LanguageAccept object.

property accept_mimetypes: MIMEAccept

List of mimetypes this client supports as MIMEAccept object.

access_control_request_headers

Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set access_control_allow_headers on the response to indicate which headers are allowed.

access_control_request_method

Sent with a preflight request to indicate which method will be used for the cross origin request. Set access_control_allow_methods on the response to indicate which methods are allowed.

property access_route: list[str]

If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server.

classmethod application(f)

Decorate a function as responder that accepts the request as the last argument. This works like the 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.

Parameters:

f (t.Callable[[Request], WSGIApplication]) – the WSGI callable to decorate

Returns:

a new WSGI callable

Return type:

WSGIApplication

property args: MultiDict[str, str]

The parsed URL parameters (the part in the URL after the question mark).

By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important.

Changelog

Changed in version 2.3: Invalid bytes remain percent encoded.

property authorization: Authorization | None

The Authorization header parsed into an Authorization object. None if the header is not present.

Changelog

Changed in version 2.3: Authorization is no longer a dict. The token attribute was added for auth schemes that use a token instead of parameters.

property base_url: str

Like url but without the query string.

property cache_control: RequestCacheControl

A RequestCacheControl object for the incoming cache control headers.

close()

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.

Changelog

New in version 0.9.

Return type:

None

content_encoding

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.

Changelog

New in version 0.9.

property content_length: int | None

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.

content_md5

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.)

Changelog

New in version 0.9.

content_type

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.

property cookies: ImmutableMultiDict[str, str]

A dict with the contents of all cookies transmitted with the request.

property data: bytes

The raw data read from stream. Will be empty if the request represents form data.

To get the raw data even if it represents form data, use get_data().

date

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.

Changelog

Changed in version 2.0: The datetime object is timezone-aware.

dict_storage_class

alias of ImmutableMultiDict

environ: WSGIEnvironment

The WSGI environment containing HTTP headers and information from the WSGI server.

property files: ImmutableMultiDict[str, FileStorage]

MultiDict object containing all uploaded files. Each key in files is the name from the <input type="file" name="">. Each value in files is a Werkzeug FileStorage object.

It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem.

Note that 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 MultiDict / FileStorage documentation for more details about the used data structure.

property form: ImmutableMultiDict[str, str]

The form parameters. By default an ImmutableMultiDict is returned from this function. This can be changed by setting 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 files attribute.

Changelog

Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests.

form_data_parser_class

alias of FormDataParser

classmethod from_values(*args, **kwargs)

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 (Client) that allows to create multipart requests, support for cookies etc.

This accepts the same options as the EnvironBuilder.

Changelog

Changed in version 0.5: This method now accepts the same arguments as EnvironBuilder. Because of this the environ parameter is now called environ_overrides.

Returns:

request object

Parameters:
  • args (Any) –

  • kwargs (Any) –

Return type:

Request

property full_path: str

Requested path, including the query string.

get_data(cache: bool = True, as_text: Literal[False] = False, parse_form_data: bool = False) bytes
get_data(cache: bool = True, as_text: Literal[True] = False, parse_form_data: bool = False) str

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.

Changelog

New in version 0.9.

get_json(force: bool = False, silent: Literal[False] = False, cache: bool = True) Any
get_json(force: bool = False, silent: bool = False, cache: bool = True) Any | None

Parse data as JSON.

If the mimetype does not indicate JSON (application/json, see is_json), or parsing fails, on_json_loading_failed() is called and its return value is used as the return value. By default this raises a 415 Unsupported Media Type resp.

Parameters:
  • force – Ignore the mimetype and always try to parse JSON.

  • silent – Silence mimetype and parsing errors, and return None instead.

  • cache – Store the parsed JSON to return for subsequent calls.

Changelog

Changed in version 2.3: Raise a 415 error instead of 400.

Changed in version 2.1: Raise a 400 error if the content type is incorrect.

headers

The headers received with the request.

property host: str

The host name the request was made to, including the port if it’s non-standard. Validated with trusted_hosts.

property host_url: str

The request URL scheme and host only.

property if_match: ETags

An object containing all the etags in the If-Match header.

Return type:

ETags

property if_modified_since: datetime | None

The parsed If-Modified-Since header as a datetime object.

Changelog

Changed in version 2.0: The datetime object is timezone-aware.

property if_none_match: ETags

An object containing all the etags in the If-None-Match header.

Return type:

ETags

property if_range: IfRange

The parsed If-Range header.

Changelog

Changed in version 2.0: IfRange.date is timezone-aware.

New in version 0.7.

property if_unmodified_since: datetime | None

The parsed If-Unmodified-Since header as a datetime object.

Changelog

Changed in version 2.0: The datetime object is timezone-aware.

input_stream

The raw WSGI input stream, without any safety checks.

This is dangerous to use. It does not guard against infinite streams or reading past content_length or max_content_length.

Use stream instead.

property is_json: bool

Check if the mimetype indicates JSON data, either application/json or application/*+json.

is_multiprocess

boolean that is True if the application is served by a WSGI server that spawns multiple processes.

is_multithread

boolean that is True if the application is served by a multithreaded WSGI server.

is_run_once

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.

property is_secure: bool

True if the request was made with a secure protocol (HTTPS or WSS).

property json: Any | None

The parsed JSON data if mimetype indicates JSON (application/json, see is_json).

Calls get_json() with default arguments.

If the request content type is not application/json, this will raise a 415 Unsupported Media Type error.

Changelog

Changed in version 2.3: Raise a 415 error instead of 400.

Changed in version 2.1: Raise a 400 error if the content type is incorrect.

json_module = <module 'json' from '/home/docs/.asdf/installs/python/3.10.13/lib/python3.10/json/__init__.py'>

A module or other object that has dumps and loads functions that match the API of the built-in json module.

list_storage_class

alias of ImmutableList

make_form_data_parser()

Creates the form data parser. Instantiates the form_data_parser_class with some parameters.

Changelog

New in version 0.8.

Return type:

FormDataParser

max_content_length: int | None = None

the maximum content length. This is forwarded to the form data parsing function (parse_form_data()). When set and the form or files attribute is accessed and the parsing fails because more than the specified value is transmitted a RequestEntityTooLarge exception is raised.

Changelog

New in version 0.5.

max_form_memory_size: int | None = None

the maximum form field size. This is forwarded to the form data parsing function (parse_form_data()). When set and the form or files attribute is accessed and the data in memory for post data is longer than the specified value a RequestEntityTooLarge exception is raised.

Changelog

New in version 0.5.

max_form_parts = 1000

The maximum number of multipart parts to parse, passed to form_data_parser_class. Parsing form data with more than this many parts will raise RequestEntityTooLarge.

Changelog

New in version 2.2.3.

max_forwards

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.

method

The method the request was made with, such as GET.

property mimetype: str

Like 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'.

property mimetype_params: 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'}.

on_json_loading_failed(e)

Called if get_json() fails and isn’t silenced.

If this method returns a value, it is used as the return value for get_json(). The default implementation raises BadRequest.

Parameters:

e (ValueError | None) – If parsing failed, this is the exception. It will be None if the content type wasn’t application/json.

Return type:

Any

Changelog

Changed in version 2.3: Raise a 415 error instead of 400.

origin

The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed.

parameter_storage_class

alias of ImmutableMultiDict

path

The path part of the URL after root_path. This is the path used for routing within the application.

property pragma: 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.

query_string

The part of the URL after the “?”. This is the raw value, use args for the parsed values.

property range: Range | None

The parsed Range header.

Changelog

New in version 0.7.

Return type:

Range

referrer

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).

remote_addr

The address of the client sending the request.

remote_user

If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.

root_path

The prefix that the application is mounted under, without a trailing slash. path comes after this.

property root_url: str

The request URL scheme, host, and root path. This is the root that the application is accessed from.

scheme

The URL scheme of the protocol the request used, such as https or wss.

property script_root: str

Alias for self.root_path. environ["SCRIPT_ROOT"] without a trailing slash.

server

The address of the server. (host, port), (path, None) for unix sockets, or None if not known.

shallow: bool

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.

property stream: IO[bytes]

The WSGI input stream, with safety checks. This stream can only be consumed once.

Use get_data() to get the full data as bytes or text. The data attribute will contain the full bytes only if they do not represent form data. The form attribute will contain the parsed form data in that case.

Unlike input_stream, this stream guards against infinite streams or reading past content_length or max_content_length.

If max_content_length is set, it can be enforced on streams if wsgi.input_terminated is set. Otherwise, an empty stream is returned.

If the limit is reached before the underlying stream is exhausted (such as a file that is too large, or an infinite stream), the remaining contents of the stream cannot be read safely. Depending on how the server handles this, clients may show a “connection reset” failure instead of seeing the 413 response.

Changelog

Changed in version 2.3: Check max_content_length preemptively and while reading.

Changed in version 0.9: The stream is always set (but may be consumed) even if form parsing was accessed first.

trusted_hosts: list[str] | None = None

Valid host names when handling requests. By default all hosts are trusted, which means that whatever the client says 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 the application is being run behind one).

Changelog

New in version 0.9.

property url: str

The full request URL with the scheme, host, root path, path, and query string.

property url_root: str

Alias for root_url. The URL with scheme, host, and root path. For example, https://example.com/app/.

property user_agent: UserAgent

The user agent. Use user_agent.string to get the header value. Set user_agent_class to a subclass of UserAgent to provide parsing for the other properties or other extended data.

Changelog

Changed in version 2.1: The built-in parser was removed. Set user_agent_class to a UserAgent subclass to parse data from the string.

user_agent_class

alias of UserAgent

property values: CombinedMultiDict[str, str]

A werkzeug.datastructures.CombinedMultiDict that combines args and form.

For GET requests, only args are present, not form.

Changelog

Changed in version 2.0: For GET requests, only args are present, not form.

property want_form_data_parsed: bool

True if the request method carries content. By default this is true if a Content-Type is sent.

Changelog

New in version 0.8.

class werkzeug.wrappers.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)

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 send_file() helper should be used in that case.

The response object is itself a WSGI application callable. When called (__call__()) with environ and start_response, it will pass its status and headers to start_response then return its body as an iterable.

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)
Parameters:
  • response (Iterable[str] | Iterable[bytes]) – 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.

  • status (int | str | HTTPStatus | None) – 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.

  • headers (Headers) – A Headers object, or a list of (key, value) tuples that will be converted to a Headers object.

  • mimetype (str | None) – 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.

  • content_type (str | None) – The full content type of the response. Overrides building the value from mimetype.

  • direct_passthrough (bool) – 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 send_file() instead of setting this manually.

Changelog

Changed in version 2.1: Old BaseResponse and mixin classes were removed.

Changed in version 2.0: Combine BaseResponse and mixins into a single Response class.

Changed in version 0.5: The direct_passthrough parameter was added.

__call__(environ, start_response)

Process this response as WSGI application.

Parameters:
  • environ (WSGIEnvironment) – the WSGI environment.

  • start_response (StartResponse) – the response callable provided by the WSGI server.

Returns:

an application iterator

Return type:

t.Iterable[bytes]

_ensure_sequence(mutable=False)

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.

Changelog

New in version 0.6.

Parameters:

mutable (bool) –

Return type:

None

accept_ranges

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.

Changelog

New in version 0.7.

property access_control_allow_credentials: 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.

access_control_allow_headers

Which headers can be sent with the cross origin request.

access_control_allow_methods

Which methods can be used for the cross origin request.

access_control_allow_origin

The origin or ‘*’ for any origin that may make cross origin requests.

access_control_expose_headers

Which headers can be shared by the browser to JavaScript code.

access_control_max_age

The maximum age in seconds the access control settings can be cached for.

add_etag(overwrite=False, weak=False)

Add an etag for the current response if there is none yet.

Changelog

Changed in version 2.0: SHA-1 is used to generate the value. MD5 may not be available in some environments.

Parameters:
Return type:

None

age

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.

property allow: HeaderSet

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.

autocorrect_location_header = False

If a redirect Location header is a relative URL, make it an absolute URL, including scheme and domain.

Changelog

Changed in version 2.1: This is disabled by default, so responses will send relative redirects.

New in version 0.8.

automatically_set_content_length = True

Should this response object automatically set the content-length header if possible? This is true by default.

Changelog

New in version 0.8.

property cache_control: 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.

calculate_content_length()

Returns the content length if available or None otherwise.

Return type:

int | None

call_on_close(func)

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.

Changelog

New in version 0.6.

Parameters:

func (Callable[[], Any]) –

Return type:

Callable[[], Any]

close()

Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it.

Changelog

New in version 0.9: Can now be used in a with statement.

Return type:

None

content_encoding

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.

property content_language: HeaderSet

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.

content_length

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

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_md5

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.)

property content_range: ContentRange

The Content-Range header as a ContentRange object. Available even if the header is not set.

Changelog

New in version 0.7.

property content_security_policy: ContentSecurityPolicy

The Content-Security-Policy header as a ContentSecurityPolicy object. Available even if the header is not set.

The Content-Security-Policy header adds an additional layer of security to help detect and mitigate certain types of attacks.

property content_security_policy_report_only: ContentSecurityPolicy

The Content-Security-policy-report-only header as a ContentSecurityPolicy object. Available even if the header is not set.

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.

content_type

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.

cross_origin_embedder_policy

Prevents a document from loading any cross-origin resources that do not explicitly grant the document permission. Values must be a member of the werkzeug.http.COEP enum.

cross_origin_opener_policy

Allows control over sharing of browsing context group with cross-origin documents. Values must be a member of the werkzeug.http.COOP enum.

property data: bytes | str

A descriptor that calls get_data() and set_data().

date

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.

Changelog

Changed in version 2.0: The datetime object is timezone-aware.

default_mimetype: str | None = 'text/plain'

the default mimetype if none is provided.

default_status = 200

the default status if none is provided.

Delete a cookie. Fails silently if key doesn’t exist.

Parameters:
  • key (str) – the key (name) of the cookie to be deleted.

  • path (str | None) – if the cookie that should be deleted was limited to a path, the path has to be defined here.

  • domain (str | None) – if the cookie that should be deleted was limited to a domain, that domain has to be defined here.

  • secure (bool) – If True, the cookie will only be available via HTTPS.

  • httponly (bool) – Disallow JavaScript access to the cookie.

  • samesite (str | None) – Limit the scope of the cookie to only be attached to requests that are “same-site”.

Return type:

None

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 send_file() instead of setting this manually.

expires

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.

Changelog

Changed in version 2.0: The datetime object is timezone-aware.

classmethod force_type(response, environ=None)

Enforce that the WSGI response is a response object of the current type. Werkzeug will use the Response internally in many situations like the exceptions. If you call get_response() on an exception you will get back a regular 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!

Parameters:
  • response (Response) – a response object or wsgi application.

  • environ (WSGIEnvironment | None) – a WSGI environment object.

Returns:

a response object.

Return type:

Response

freeze()

Make the response object ready to be pickled. Does the following:

  • Buffer the response into a list, ignoring implicity_sequence_conversion and direct_passthrough.

  • Set the Content-Length header.

  • Generate an ETag header if one is not already set.

Changelog

Changed in version 2.1: Removed the no_etag parameter.

Changed in version 2.0: An ETag header is always added.

Changed in version 0.6: The Content-Length header is set.

Return type:

None

classmethod from_app(app, environ, buffered=False)

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.

Parameters:
  • app (WSGIApplication) – the WSGI application to execute.

  • environ (WSGIEnvironment) – the WSGI environment to execute against.

  • buffered (bool) – set to True to enforce buffering.

Returns:

a response object.

Return type:

Response

get_app_iter(environ)

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.

Changelog

New in version 0.6.

Parameters:

environ (WSGIEnvironment) – the WSGI environment of the request.

Returns:

a response iterable.

Return type:

t.Iterable[bytes]

get_data(as_text: Literal[False] = False) bytes
get_data(as_text: Literal[True]) str

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 implicit_sequence_conversion to False.

If as_text is set to True the return value will be a decoded string.

Changelog

New in version 0.9.

get_etag()

Return a tuple in the form (etag, is_weak). If there is no ETag the return value is (None, None).

Return type:

tuple[str, bool] | tuple[None, None]

get_json(force: bool = False, silent: Literal[False] = False) Any
get_json(force: bool = False, silent: bool = False) Any | None

Parse data as JSON. Useful during testing.

If the mimetype does not indicate JSON (application/json, see is_json), this returns None.

Unlike Request.get_json(), the result is not cached.

Parameters:
  • force – Ignore the mimetype and always try to parse JSON.

  • silent – Silence parsing errors and return None instead.

get_wsgi_headers(environ)

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.

Changelog

Changed in version 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.

Parameters:

environ (WSGIEnvironment) – the WSGI environment of the request.

Returns:

returns a new Headers object.

Return type:

Headers

get_wsgi_response(environ)

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.

Changelog

New in version 0.6.

Parameters:

environ (WSGIEnvironment) – the WSGI environment of the request.

Returns:

an (app_iter, status, headers) tuple.

Return type:

tuple[t.Iterable[bytes], str, list[tuple[str, str]]]

implicit_sequence_conversion = True

if set to False accessing properties on the response object will not try to consume the response iterator and convert it into a list.

Changelog

New in version 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.

property is_json: bool

Check if the mimetype indicates JSON data, either application/json or application/*+json.

property is_sequence: 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.

Changelog

New in version 0.6.

property is_streamed: 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.

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 direct_passthrough was activated.

Return type:

Iterator[bytes]

property json: Any | None

The parsed JSON data if mimetype indicates JSON (application/json, see is_json).

Calls get_json() with default arguments.

json_module = <module 'json' from '/home/docs/.asdf/installs/python/3.10.13/lib/python3.10/json/__init__.py'>

A module or other object that has dumps and loads functions that match the API of the built-in json module.

last_modified

The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified.

Changelog

Changed in version 2.0: The datetime object is timezone-aware.

location

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.

make_conditional(request_or_environ, accept_ranges=False, complete_length=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 io.IOBase. Objects returned by wrap_file() automatically implement those methods.

It does not remove the body of the response because that’s something the __call__() function does for us automatically.

Returns self so that you can do return resp.make_conditional(req) but modifies the object in-place.

Parameters:
  • request_or_environ (WSGIEnvironment | Request) – a request object or WSGI environment to be used to make the response conditional against.

  • accept_ranges (bool | str) – 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 it’s a string, it will use this value.

  • complete_length (int | None) – 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:

RequestedRangeNotSatisfiable if Range header could not be parsed or satisfied.

Return type:

Response

Changelog

Changed in version 2.0: Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error.

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. This also encodes all the items.

Changelog

New in version 0.6.

Return type:

None

Warn if a cookie header exceeds this size. The default, 4093, should be safely supported by most browsers. 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.

Changelog

New in version 0.13.

property mimetype: str | None

The mimetype (content type without charset etc.)

property mimetype_params: 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'}.

Changelog

New in version 0.5.

response: Iterable[str] | Iterable[bytes]

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.

property retry_after: datetime | None

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.

Changelog

Changed in version 2.0: The datetime object is timezone-aware.

Sets a cookie.

A warning is raised if the size of the cookie header exceeds max_cookie_size, but the header will still be set.

Parameters:
  • key (str) – the key (name) of the cookie to be set.

  • value (str) – the value of the cookie.

  • max_age (timedelta | int | None) – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.

  • expires (str | datetime | int | float | None) – should be a datetime object or UNIX timestamp.

  • path (str | None) – limits the cookie to a given path, per default it will span the whole domain.

  • domain (str | None) – 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.

  • secure (bool) – If True, the cookie will only be available via HTTPS.

  • httponly (bool) – Disallow JavaScript access to the cookie.

  • samesite (str | None) – Limit the scope of the cookie to only be attached to requests that are “same-site”.

Return type:

None

set_data(value)

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).

Changelog

New in version 0.9.

Parameters:

value (bytes | str) –

Return type:

None

set_etag(etag, weak=False)

Set the etag, and override the old one if there was one.

Parameters:
Return type:

None

property status: str

The HTTP status code as a string.

property status_code: int

The HTTP status code as a number.

property stream: ResponseStream

The response iterable as write-only stream.

property vary: HeaderSet

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.

property www_authenticate: WWWAuthenticate

The WWW-Authenticate header parsed into a WWWAuthenticate object. Modifying the object will modify the header value.

This header is not set by default. To set this header, assign an instance of WWWAuthenticate to this attribute.

response.www_authenticate = WWWAuthenticate(
    "basic", {"realm": "Authentication Required"}
)

Multiple values for this header can be sent to give the client multiple options. Assign a list to set multiple headers. However, modifying the items in the list will not automatically update the header values, and accessing this attribute will only ever return the first value.

To unset this header, assign None or use del.

Changelog

Changed in version 2.3: This attribute can be assigned to to set the header. A list can be assigned to set multiple header values. Use del to unset the header.

Changed in version 2.3: WWWAuthenticate is no longer a dict. The token attribute was added for auth challenges that use a token instead of parameters.