module documentation

Undocumented

Class COEP Cross Origin Embedder Policies
Class COOP Cross Origin Opener Policies
Function cookie​_date Format a datetime object or timestamp into an RFC 2822 date string for Set-Cookie expires.
Function dump​_age Formats the duration as a base-10 integer.
Function dump​_cookie Create a Set-Cookie header without the Set-Cookie prefix.
Function dump​_csp​_header Dump a Content Security Policy header.
Function dump​_header No summary
Function dump​_options​_header The reverse function to parse_options_header.
Function generate​_etag Generate an etag for some data.
Function http​_date Format a datetime object or timestamp into an RFC 2822 date string.
Function is​_byte​_range​_valid Checks if a given byte content range is valid for the given length.
Function is​_entity​_header Check if a header is an entity header.
Function is​_hop​_by​_hop​_header Check if a header is an HTTP/1.1 "Hop-by-Hop" header.
Function is​_resource​_modified Convenience method for conditional requests.
Function parse​_accept​_header Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction.
Function parse​_age Parses a base-10 integer count of seconds into a timedelta.
Function parse​_authorization​_header No summary
Function parse​_cache​_control​_header Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements.
Function parse​_content​_range​_header Parses a range header into a ~werkzeug.datastructures.ContentRange object or None if parsing is not possible.
Function parse​_cookie Parse a cookie from a string or WSGI environ.
Function parse​_csp​_header Parse a Content Security Policy header.
Function parse​_date Parse an RFC 2822 date into a timezone-aware datetime.datetime object, or None if parsing fails.
Function parse​_dict​_header Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the cls argument):
Function parse​_etags Parse an etag header.
Function parse​_if​_range​_header Parses an if-range header which can be an etag or a date. Returns a ~werkzeug.datastructures.IfRange object.
Function parse​_list​_header Parse lists as described by RFC 2068 Section 2.
Function parse​_options​_header Parse a Content-Type like header into a tuple with the content type and the options:
Function parse​_range​_header No summary
Function parse​_set​_header Parse a set-like header and return a ~werkzeug.datastructures.HeaderSet object:
Function parse​_www​_authenticate​_header Parse an HTTP WWW-Authenticate header into a ~werkzeug.datastructures.WWWAuthenticate object.
Function quote​_etag Quote an etag.
Function quote​_header​_value Quote a header value if necessary.
Function remove​_entity​_headers No summary
Function remove​_hop​_by​_hop​_headers Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or Headers object. This operation works in-place.
Function unquote​_etag Unquote a single etag:
Function unquote​_header​_value Unquotes a header value. (Reversal of quote_header_value). This does not use the real unquoting but what browsers are actually using for quoting.
Constant HTTP​_STATUS​_CODES Undocumented
Variable ​_accept​_re Undocumented
Variable ​_entity​_headers Undocumented
Variable ​_etag​_re Undocumented
Variable ​_hop​_by​_hop​_headers Undocumented
Variable ​_option​_header​_piece​_re Undocumented
Variable ​_option​_header​_start​_mime​_type Undocumented
Variable ​_t​_cc​_update Undocumented
Variable ​_t​_csp​_update Undocumented
Variable _​TAny​Accept Undocumented
Variable _​TAny​CC Undocumented
Variable _​TAny​CSP Undocumented
Variable ​_token​_chars Undocumented
def cookie_date(expires=None):

Format a datetime object or timestamp into an RFC 2822 date string for Set-Cookie expires.

Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use http_date instead.
Parameters
expires:t.Optional[t.Union[datetime, date, int, float, struct_time]]Undocumented
Returns
strUndocumented
def dump_age(age=None):
Formats the duration as a base-10 integer.
Parameters
age:t.Optional[t.Union[timedelta, int]]should be an integer number of seconds, a datetime.timedelta object, or, if the age is unknown, None (default).
Returns
t.Optional[str]Undocumented
def dump_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, charset='utf-8', sync_expires=True, max_size=4093, samesite=None):

Create a Set-Cookie header without the Set-Cookie prefix.

The return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. It's tunneled through latin1 as required by PEP 3333.

The return value is not ASCII safe if the key contains unicode characters. This is technically against the specification but happens in the wild. It's strongly recommended to not use non-ASCII values for the keys.

Changed in version 1.0.0: The string 'None' is accepted for samesite.
Parameters
key:strUndocumented
value:t.Union[bytes, str]Undocumented
max​_age:t.Optional[t.Union[timedelta, int]]should be a number of seconds, or None (default) if the cookie should last only as long as the client's browser session. Additionally timedelta objects are accepted, too.
expires:t.Optional[t.Union[str, datetime, int, float]]should be a datetime object or unix timestamp.
path:t.Optional[str]limits the cookie to a given path, per default it will span the whole domain.
domain:t.Optional[str]Use this 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:boolThe cookie will only be available via HTTPS
httponly:booldisallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers.
charset:strthe encoding for string values.
sync​_expires:boolautomatically set expires if max_age is defined but expires not.
max​_size:intWarn if the final header value exceeds this size. The default, 4093, should be safely supported by most browsers. Set to 0 to disable this check.
samesite:t.Optional[str]Limits the scope of the cookie such that it will only be attached to requests if those requests are same-site.
Returns
strUndocumented
def dump_csp_header(header):

Dump a Content Security Policy header.

These are structured into policies such as "default-src 'self'; script-src 'self'".

New in version 1.0.0: Support for Content Security Policy headers was added.
Parameters
header:ds.ContentSecurityPolicyUndocumented
Returns
strUndocumented
def dump_header(iterable, allow_token=True):

Dump an HTTP header again. This is the reversal of parse_list_header, parse_set_header and parse_dict_header. This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs.

>>> dump_header({'foo': 'bar baz'})
'foo="bar baz"'
>>> dump_header(('foo', 'bar baz'))
'foo, "bar baz"'
Parameters
iterable:t.Union[t.Dict[str, t.Union[str, int]], t.Iterable[str]]the iterable or dict of values to quote.
allow​_token:boolif set to False tokens as values are disallowed. See quote_header_value for more details.
Returns
strUndocumented
def dump_options_header(header, options):
The reverse function to parse_options_header.
Parameters
header:t.Optional[str]the header to dump
options:t.Mapping[str, t.Optional[t.Union[str, int]]]a dict of options to append.
Returns
strUndocumented
def generate_etag(data):

Generate an etag for some data.

Changed in version 2.0: Use SHA-1. MD5 may not be available in some environments.
Parameters
data:bytesUndocumented
Returns
strUndocumented
def http_date(timestamp=None):

Format a datetime object or timestamp into an RFC 2822 date string.

This is a wrapper for email.utils.format_datetime. It assumes naive datetime objects are in UTC instead of raising an exception.

Changed in version 2.0: Use email.utils.format_datetime. Accept date objects.
Parameters
timestamp:t.Optional[t.Union[datetime, date, int, float, struct_time]]The datetime or timestamp to format. Defaults to the current time.
Returns
strUndocumented
def is_byte_range_valid(start, stop, length):

Checks if a given byte content range is valid for the given length.

New in version 0.7.
Parameters
start:t.Optional[int]Undocumented
stop:t.Optional[int]Undocumented
length:t.Optional[int]Undocumented
Returns
boolUndocumented
def is_entity_header(header):

Check if a header is an entity header.

New in version 0.5.
Parameters
header:strthe header to test.
Returns
boolTrue if it's an entity header, False otherwise.
def is_hop_by_hop_header(header):

Check if a header is an HTTP/1.1 "Hop-by-Hop" header.

New in version 0.5.
Parameters
header:strthe header to test.
Returns
boolTrue if it's an HTTP/1.1 "Hop-by-Hop" header, False otherwise.
def is_resource_modified(environ, etag=None, data=None, last_modified=None, ignore_if_range=True):

Convenience method for conditional requests.

Changed in version 2.0: SHA-1 is used to generate an etag value for the data. MD5 may not be available in some environments.
Changed in version 1.0.0: The check is run for methods other than GET and HEAD.
Parameters
environ:WSGIEnvironmentthe WSGI environment of the request to be checked.
etag:t.Optional[str]the etag for the response for comparison.
data:t.Optional[bytes]or alternatively the data of the response to automatically generate an etag using generate_etag.
last​_modified:t.Optional[t.Union[datetime, str]]an optional date of the last modification.
ignore​_if​_range:boolIf False, If-Range header will be taken into account.
Returns
boolTrue if the resource was modified, otherwise False.
def parse_accept_header(value, cls=None):

Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction.

Returns a new Accept object (basically a list of (value, quality) tuples sorted by the quality with some additional accessor methods).

The second parameter can be a subclass of Accept that is created with the parsed values and returned.

Parameters
value:t.Optional[str]the accept header string to be parsed.
cls:t.Optional[t.Type[_TAnyAccept]]the wrapper class for the return value (can be Accept or a subclass thereof)
Returns
_TAnyAcceptan instance of cls.
def parse_age(value=None):

Parses a base-10 integer count of seconds into a timedelta.

If parsing fails, the return value is None.

Parameters
value:t.Optional[str]a string consisting of an integer represented in base-10
Returns
t.Optional[timedelta]a datetime.timedelta object or None.
def parse_authorization_header(value):
Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either None if the header was invalid or not given, otherwise an ~werkzeug.datastructures.Authorization object.
Parameters
value:t.Optional[str]the authorization header to parse.
Returns
t.Optional[ds.Authorization]a ~werkzeug.datastructures.Authorization object or None.
def parse_cache_control_header(value, on_update=None, cls=None):

Parse a cache control header. The RFC differs between response and request cache control, this method does not. It's your responsibility to not use the wrong control statements.

New in version 0.5: The cls was added. If not specified an immutable ~werkzeug.datastructures.RequestCacheControl is returned.
Parameters
value:t.Optional[str]a cache control header to be parsed.
on​_update:_t_cc_updatean optional callable that is called every time a value on the ~werkzeug.datastructures.CacheControl object is changed.
cls:t.Optional[t.Type[_TAnyCC]]the class for the returned object. By default ~werkzeug.datastructures.RequestCacheControl is used.
Returns
_TAnyCCa cls object.
def parse_content_range_header(value, on_update=None):

Parses a range header into a ~werkzeug.datastructures.ContentRange object or None if parsing is not possible.

New in version 0.7.
Parameters
value:t.Optional[str]a content range header to be parsed.
on​_update:t.Optional[t.Callable[[ds.ContentRange], None]]an optional callable that is called every time a value on the ~werkzeug.datastructures.ContentRange object is changed.
Returns
t.Optional[ds.ContentRange]Undocumented
def parse_cookie(header, charset='utf-8', errors='replace', cls=None):

Parse a cookie from a string or WSGI environ.

The same key can be provided multiple times, the values are stored in-order. The default MultiDict will have the first value first, and all values can be retrieved with MultiDict.getlist.

Changed in version 1.0.0: Returns a MultiDict instead of a TypeConversionDict.
Changed in version 0.5: Returns a TypeConversionDict instead of a regular dict. The cls parameter was added.
Parameters
header:t.Union[WSGIEnvironment, str, bytes, None]The cookie header as a string, or a WSGI environ dict with a HTTP_COOKIE key.
charset:strThe charset for the cookie values.
errors:strThe error behavior for the charset decoding.
cls:t.Optional[t.Type[ds.MultiDict]]A dict-like class to store the parsed cookies in. Defaults to MultiDict.
Returns
ds.MultiDict[str, str]Undocumented
def parse_csp_header(value, on_update=None, cls=None):

Parse a Content Security Policy header.

New in version 1.0.0: Support for Content Security Policy headers was added.
Parameters
value:t.Optional[str]a csp header to be parsed.
on​_update:_t_csp_updatean optional callable that is called every time a value on the object is changed.
cls:t.Optional[t.Type[_TAnyCSP]]the class for the returned object. By default ~werkzeug.datastructures.ContentSecurityPolicy is used.
Returns
_TAnyCSPa cls object.
def parse_date(value):

Parse an RFC 2822 date into a timezone-aware datetime.datetime object, or None if parsing fails.

This is a wrapper for email.utils.parsedate_to_datetime. It returns None if parsing fails instead of raising an exception, and always returns a timezone-aware datetime object. If the string doesn't have timezone information, it is assumed to be UTC.

Changed in version 2.0: Return a timezone-aware datetime object. Use email.utils.parsedate_to_datetime.
Parameters
value:t.Optional[str]A string with a supported date format.
Returns
t.Optional[datetime]Undocumented
def parse_dict_header(value, cls=dict):

Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the cls argument):

>>> d = parse_dict_header('foo="is a fish", bar="as well"')
>>> type(d) is dict
True
>>> sorted(d.items())
[('bar', 'as well'), ('foo', 'is a fish')]

If there is no value for a key it will be None:

>>> parse_dict_header('key_without_value')
{'key_without_value': None}

To create a header from the dict again, use the dump_header function.

Changed in version 0.9: Added support for cls argument.
Parameters
value:stra string with a dict header.
cls:t.Type[dict]callable to use for storage of parsed results.
Returns
t.Dict[str, str]an instance of cls
def parse_etags(value):
Parse an etag header.
Parameters
value:t.Optional[str]the tag header to parse
Returns
ds.ETagsan ~werkzeug.datastructures.ETags object.
def parse_if_range_header(value):

Parses an if-range header which can be an etag or a date. Returns a ~werkzeug.datastructures.IfRange object.

Changed in version 2.0: If the value represents a datetime, it is timezone-aware.
New in version 0.7.
Parameters
value:t.Optional[str]Undocumented
Returns
ds.IfRangeUndocumented
def parse_list_header(value):

Parse lists as described by RFC 2068 Section 2.

In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing.

It basically works like parse_set_header just that items may appear multiple times and case sensitivity is preserved.

The return value is a standard list:

>>> parse_list_header('token, "quoted value"')
['token', 'quoted value']

To create a header from the list again, use the dump_header function.

Parameters
value:stra string with a list header.
Returns
t.List[str]list
def parse_options_header(value, multiple=False):

Parse a Content-Type like header into a tuple with the content type and the options:

>>> parse_options_header('text/html; charset=utf8')
('text/html', {'charset': 'utf8'})

This should not be used to parse Cache-Control like headers that use a slightly different format. For these headers use the parse_dict_header function.

Changed in version 0.15: RFC 2231 parameter continuations are handled.
New in version 0.5.
Parameters
value:t.Optional[str]the header to parse.
multiple:boolWhether try to parse and return multiple MIME types
Returns
t.Union[t.Tuple[str, t.Dict[str, str]], t.Tuple[t.Any, ...]](mimetype, options) or (mimetype, options, mimetype, options, …) if multiple=True
def parse_range_header(value, make_inclusive=True):

Parses a range header into a ~werkzeug.datastructures.Range object. If the header is missing or malformed None is returned. ranges is a list of (start, stop) tuples where the ranges are non-inclusive.

New in version 0.7.
Parameters
value:t.Optional[str]Undocumented
make​_inclusive:boolUndocumented
Returns
t.Optional[ds.Range]Undocumented
def parse_set_header(value, on_update=None):

Parse a set-like header and return a ~werkzeug.datastructures.HeaderSet object:

>>> hs = parse_set_header('token, "quoted value"')

The return value is an object that treats the items case-insensitively and keeps the order of the items:

>>> 'TOKEN' in hs
True
>>> hs.index('quoted value')
1
>>> hs
HeaderSet(['token', 'quoted value'])

To create a header from the HeaderSet again, use the dump_header function.

Parameters
value:t.Optional[str]a set header to be parsed.
on​_update:t.Optional[t.Callable[[ds.HeaderSet], None]]an optional callable that is called every time a value on the ~werkzeug.datastructures.HeaderSet object is changed.
Returns
ds.HeaderSeta ~werkzeug.datastructures.HeaderSet
def parse_www_authenticate_header(value, on_update=None):
Parse an HTTP WWW-Authenticate header into a ~werkzeug.datastructures.WWWAuthenticate object.
Parameters
value:t.Optional[str]a WWW-Authenticate header to parse.
on​_update:t.Optional[t.Callable[[ds.WWWAuthenticate], None]]an optional callable that is called every time a value on the ~werkzeug.datastructures.WWWAuthenticate object is changed.
Returns
ds.WWWAuthenticatea ~werkzeug.datastructures.WWWAuthenticate object.
def quote_etag(etag, weak=False):
Quote an etag.
Parameters
etag:strthe etag to quote.
weak:boolset to True to tag it "weak".
Returns
strUndocumented
def quote_header_value(value, extra_chars='', allow_token=True):

Quote a header value if necessary.

New in version 0.5.
Parameters
value:t.Union[str, int]the value to quote.
extra​_chars:stra list of extra characters to skip quoting.
allow​_token:boolif this is enabled token values are returned unchanged.
Returns
strUndocumented
def remove_entity_headers(headers, allowed=('expires', 'content-location')):

Remove all entity headers from a list or Headers object. This operation works in-place. Expires and Content-Location headers are by default not removed. The reason for this is RFC 2616 section 10.3.5 which specifies some entity headers that should be sent.

Changed in version 0.5: added allowed parameter.
Parameters
headers:t.Union[ds.Headers, t.List[t.Tuple[str, str]]]a list or Headers object.
allowed:t.Iterable[str]a list of headers that should still be allowed even though they are entity headers.
def remove_hop_by_hop_headers(headers):

Remove all HTTP/1.1 "Hop-by-Hop" headers from a list or Headers object. This operation works in-place.

New in version 0.5.
Parameters
headers:t.Union[ds.Headers, t.List[t.Tuple[str, str]]]a list or Headers object.
def unquote_etag(etag):

Unquote a single etag:

>>> unquote_etag('W/"bar"')
('bar', True)
>>> unquote_etag('"bar"')
('bar', False)
Parameters
etag:t.Optional[str]the etag identifier to unquote.
Returns
t.Union[t.Tuple[str, bool], t.Tuple[None, None]]a (etag, weak) tuple.
def unquote_header_value(value, is_filename=False):

Unquotes a header value. (Reversal of quote_header_value). This does not use the real unquoting but what browsers are actually using for quoting.

New in version 0.5.
Parameters
value:strthe header value to unquote.
is​_filename:boolThe value represents a filename or path.
Returns
strUndocumented
HTTP_STATUS_CODES: dict[int, str] =

Undocumented

Value
{100: 'Continue',
 101: 'Switching Protocols',
 102: 'Processing',
 103: 'Early Hints',
 200: 'OK',
 201: 'Created',
 202: 'Accepted',
...
_accept_re =

Undocumented

_entity_headers =

Undocumented

_etag_re =

Undocumented

_hop_by_hop_headers =

Undocumented

_option_header_piece_re =

Undocumented

_option_header_start_mime_type =

Undocumented

_t_cc_update =

Undocumented

_t_csp_update =

Undocumented

_TAnyAccept =

Undocumented

_TAnyCC =

Undocumented

_TAnyCSP =

Undocumented

_token_chars =

Undocumented