doc_content
stringlengths
1
386k
doc_id
stringlengths
5
188
werkzeug.wsgi.get_current_url(environ, root_only=False, strip_querystring=False, host_only=False, trusted_hosts=None) Recreate the URL for a request from the parts in a WSGI environment. The URL is an IRI, not a URI, so it may contain Unicode characters. Use iri_to_uri() to convert it to ASCII. Parameters environ (WSGIEnvironment) – The WSGI environment to get the URL parts from. root_only (bool) – Only build the root path, don’t include the remaining path or query string. strip_querystring (bool) – Don’t include the query string. host_only (bool) – Only build the scheme and host. trusted_hosts (Optional[Iterable[str]]) – A list of trusted host names to validate the host against. Return type str
werkzeug.wsgi.index#werkzeug.wsgi.get_current_url
werkzeug.filesystem.get_filesystem_encoding() Returns the filesystem encoding that should be used. Note that this is different from the Python understanding of the filesystem encoding which might be deeply flawed. Do not use this value against Python’s string APIs because it might be different. See The Filesystem for the exact behavior. The concept of a filesystem encoding in generally is not something you should rely on. As such if you ever need to use this function except for writing wrapper code reconsider. Return type str
werkzeug.filesystem.index#werkzeug.filesystem.get_filesystem_encoding
werkzeug.wsgi.get_host(environ, trusted_hosts=None) Return the host for the given WSGI environment. The Host header is preferred, then SERVER_NAME if it’s not set. The returned host will only contain the port if it is different than the standard port for the protocol. Optionally, verify that the host is trusted using host_is_trusted() and raise a SecurityError if it is not. Parameters environ (WSGIEnvironment) – A WSGI environment dict. trusted_hosts (Optional[Iterable[str]]) – A list of trusted host names. Returns Host, with port if necessary. Raises SecurityError – If the host is not trusted. Return type str
werkzeug.wsgi.index#werkzeug.wsgi.get_host
werkzeug.wsgi.get_input_stream(environ, safe_fallback=True) Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length. If content length is not set, the stream will be empty for safety reasons. If the WSGI server supports chunked or infinite streams, it should set the wsgi.input_terminated value in the WSGI environ to indicate that. Changelog New in version 0.9. Parameters environ (WSGIEnvironment) – the WSGI environ to fetch the stream from. safe_fallback (bool) – use an empty stream as a safe fallback when the content length is not set. Disabling this allows infinite streams, which can be a denial-of-service risk. Return type BinaryIO
werkzeug.wsgi.index#werkzeug.wsgi.get_input_stream
werkzeug.wsgi.get_path_info(environ, charset='utf-8', errors='replace') Return the PATH_INFO from the WSGI environment and decode it unless charset is None. Parameters environ (WSGIEnvironment) – WSGI environment to get the path from. charset (str) – The charset for the path info, or None if no decoding should be performed. errors (str) – The decoding error handling. Return type str Changelog New in version 0.9.
werkzeug.wsgi.index#werkzeug.wsgi.get_path_info
werkzeug.wsgi.get_query_string(environ) Returns the QUERY_STRING from the WSGI environment. This also takes care of the WSGI decoding dance. The string returned will be restricted to ASCII characters. Parameters environ (WSGIEnvironment) – WSGI environment to get the query string from. Return type str Changelog New in version 0.9.
werkzeug.wsgi.index#werkzeug.wsgi.get_query_string
werkzeug.wsgi.get_script_name(environ, charset='utf-8', errors='replace') Return the SCRIPT_NAME from the WSGI environment and decode it unless charset is set to None. Parameters environ (WSGIEnvironment) – WSGI environment to get the path from. charset (str) – The charset for the path, or None if no decoding should be performed. errors (str) – The decoding error handling. Return type str Changelog New in version 0.9.
werkzeug.wsgi.index#werkzeug.wsgi.get_script_name
class werkzeug.datastructures.Headers([defaults]) An object that stores some headers. It has a dict-like interface, but is ordered, can store the same key multiple times, and iterating yields (key, value) pairs instead of only keys. This data structure is useful if you want a nicer way to handle WSGI headers which are stored as tuples in a list. From Werkzeug 0.3 onwards, the KeyError raised by this class is also a subclass of the BadRequest HTTP exception and will render a page for a 400 BAD REQUEST if caught in a catch-all for HTTP exceptions. Headers is mostly compatible with the Python wsgiref.headers.Headers class, with the exception of __getitem__. wsgiref will return None for headers['missing'], whereas Headers will raise a KeyError. To create a new Headers object pass it a list or dict of headers which are used as default values. This does not reuse the list passed to the constructor for internal usage. Parameters defaults – The list of default values for the Headers. Changelog Changed in version 0.9: This data structure now stores unicode values similar to how the multi dicts do it. The main difference is that bytes can be set as well which will automatically be latin1 decoded. Changed in version 0.9: The linked() function was removed without replacement as it was an API that does not support the changes to the encoding model. add(_key, _value, **kw) Add a new header tuple to the list. Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes: >>> d = Headers() >>> d.add('Content-Type', 'text/plain') >>> d.add('Content-Disposition', 'attachment', filename='foo.png') The keyword argument dumping uses dump_options_header() behind the scenes. Changelog New in version 0.4.1: keyword arguments were added for wsgiref compatibility. add_header(_key, _value, **_kw) Add a new header tuple to the list. An alias for add() for compatibility with the wsgiref add_header() method. clear() Clears all headers. extend(*args, **kwargs) Extend headers in this object with items from another object containing header items as well as keyword arguments. To replace existing keys instead of extending, use update() instead. If provided, the first argument can be another Headers object, a MultiDict, dict, or iterable of pairs. Changelog Changed in version 1.0: Support MultiDict. Allow passing kwargs. get(key, default=None, type=None, as_bytes=False) Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found: >>> d = Headers([('Content-Length', '42')]) >>> d.get('Content-Length', type=int) 42 Changelog New in version 0.9: Added support for as_bytes. Parameters key – The key to be looked up. default – The default value to be returned if the key can’t be looked up. If not further specified None is returned. type – A callable that is used to cast the value in the Headers. If a ValueError is raised by this callable the default value is returned. as_bytes – return bytes instead of strings. get_all(name) Return a list of all the values for the named field. This method is compatible with the wsgiref get_all() method. getlist(key, type=None, as_bytes=False) Return the list of items for a given key. If that key is not in the Headers, the return value will be an empty list. Just like get(), getlist() accepts a type parameter. All items will be converted with the callable defined there. Changelog New in version 0.9: Added support for as_bytes. Parameters key – The key to be looked up. type – A callable that is used to cast the value in the Headers. If a ValueError is raised by this callable the value will be removed from the list. as_bytes – return bytes instead of strings. Returns a list of all the values for the key. has_key(key) Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use key in data instead. pop(key=None, default=no value) Removes and returns a key or index. Parameters key – The key to be popped. If this is an integer the item at that position is removed, if it’s a string the value for that key is. If the key is omitted or None the last item is removed. Returns an item. popitem() Removes a key or index and returns a (key, value) item. remove(key) Remove a key. Parameters key – The key to be removed. set(_key, _value, **kw) Remove all header tuples for key and add a new one. The newly added key either appears at the end of the list if there was no entry or replaces the first one. Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes. See add() for more information. Changelog Changed in version 0.6.1: set() now accepts the same arguments as add(). Parameters key – The key to be inserted. value – The value to be inserted. setdefault(key, default) Return the first value for the key if it is in the headers, otherwise set the header to the value given by default and return that. Parameters key – The header key to get. default – The value to set for the key if it is not in the headers. setlist(key, values) Remove any existing values for a header and add new ones. Parameters key – The header key to set. values – An iterable of values to set for the key. Changelog New in version 1.0. setlistdefault(key, default) Return the list of values for the key if it is in the headers, otherwise set the header to the list of values given by default and return that. Unlike MultiDict.setlistdefault(), modifying the returned list will not affect the headers. Parameters key – The header key to get. default – An iterable of values to set for the key if it is not in the headers. Changelog New in version 1.0. to_wsgi_list() Convert the headers into a list suitable for WSGI. Returns list update(*args, **kwargs) Replace headers in this object with items from another headers object and keyword arguments. To extend existing keys instead of replacing, use extend() instead. If provided, the first argument can be another Headers object, a MultiDict, dict, or iterable of pairs. Changelog New in version 1.0.
werkzeug.datastructures.index#werkzeug.datastructures.Headers
add(_key, _value, **kw) Add a new header tuple to the list. Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes: >>> d = Headers() >>> d.add('Content-Type', 'text/plain') >>> d.add('Content-Disposition', 'attachment', filename='foo.png') The keyword argument dumping uses dump_options_header() behind the scenes. Changelog New in version 0.4.1: keyword arguments were added for wsgiref compatibility.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.add
add_header(_key, _value, **_kw) Add a new header tuple to the list. An alias for add() for compatibility with the wsgiref add_header() method.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.add_header
clear() Clears all headers.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.clear
extend(*args, **kwargs) Extend headers in this object with items from another object containing header items as well as keyword arguments. To replace existing keys instead of extending, use update() instead. If provided, the first argument can be another Headers object, a MultiDict, dict, or iterable of pairs. Changelog Changed in version 1.0: Support MultiDict. Allow passing kwargs.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.extend
get(key, default=None, type=None, as_bytes=False) Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found: >>> d = Headers([('Content-Length', '42')]) >>> d.get('Content-Length', type=int) 42 Changelog New in version 0.9: Added support for as_bytes. Parameters key – The key to be looked up. default – The default value to be returned if the key can’t be looked up. If not further specified None is returned. type – A callable that is used to cast the value in the Headers. If a ValueError is raised by this callable the default value is returned. as_bytes – return bytes instead of strings.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.get
getlist(key, type=None, as_bytes=False) Return the list of items for a given key. If that key is not in the Headers, the return value will be an empty list. Just like get(), getlist() accepts a type parameter. All items will be converted with the callable defined there. Changelog New in version 0.9: Added support for as_bytes. Parameters key – The key to be looked up. type – A callable that is used to cast the value in the Headers. If a ValueError is raised by this callable the value will be removed from the list. as_bytes – return bytes instead of strings. Returns a list of all the values for the key.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.getlist
get_all(name) Return a list of all the values for the named field. This method is compatible with the wsgiref get_all() method.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.get_all
has_key(key) Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use key in data instead.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.has_key
pop(key=None, default=no value) Removes and returns a key or index. Parameters key – The key to be popped. If this is an integer the item at that position is removed, if it’s a string the value for that key is. If the key is omitted or None the last item is removed. Returns an item.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.pop
popitem() Removes a key or index and returns a (key, value) item.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.popitem
remove(key) Remove a key. Parameters key – The key to be removed.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.remove
set(_key, _value, **kw) Remove all header tuples for key and add a new one. The newly added key either appears at the end of the list if there was no entry or replaces the first one. Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes. See add() for more information. Changelog Changed in version 0.6.1: set() now accepts the same arguments as add(). Parameters key – The key to be inserted. value – The value to be inserted.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.set
setdefault(key, default) Return the first value for the key if it is in the headers, otherwise set the header to the value given by default and return that. Parameters key – The header key to get. default – The value to set for the key if it is not in the headers.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.setdefault
setlist(key, values) Remove any existing values for a header and add new ones. Parameters key – The header key to set. values – An iterable of values to set for the key. Changelog New in version 1.0.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.setlist
setlistdefault(key, default) Return the list of values for the key if it is in the headers, otherwise set the header to the list of values given by default and return that. Unlike MultiDict.setlistdefault(), modifying the returned list will not affect the headers. Parameters key – The header key to get. default – An iterable of values to set for the key if it is not in the headers. Changelog New in version 1.0.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.setlistdefault
to_wsgi_list() Convert the headers into a list suitable for WSGI. Returns list
werkzeug.datastructures.index#werkzeug.datastructures.Headers.to_wsgi_list
update(*args, **kwargs) Replace headers in this object with items from another headers object and keyword arguments. To extend existing keys instead of replacing, use extend() instead. If provided, the first argument can be another Headers object, a MultiDict, dict, or iterable of pairs. Changelog New in version 1.0.
werkzeug.datastructures.index#werkzeug.datastructures.Headers.update
class werkzeug.datastructures.HeaderSet(headers=None, on_update=None) Similar to the ETags class this implements a set-like structure. Unlike ETags this is case insensitive and used for vary, allow, and content-language headers. If not constructed using the parse_set_header() function the instantiation works like this: >>> hs = HeaderSet(['foo', 'bar', 'baz']) >>> hs HeaderSet(['foo', 'bar', 'baz']) add(header) Add a new header to the set. as_set(preserve_casing=False) Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. Parameters preserve_casing – if set to True the items in the set returned will have the original case like in the HeaderSet, otherwise they will be lowercase. clear() Clear the set. discard(header) Like remove() but ignores errors. Parameters header – the header to be discarded. find(header) Return the index of the header in the set or return -1 if not found. Parameters header – the header to be looked up. index(header) Return the index of the header in the set or raise an IndexError. Parameters header – the header to be looked up. remove(header) Remove a header from the set. This raises an KeyError if the header is not in the set. Changelog Changed in version 0.5: In older versions a IndexError was raised instead of a KeyError if the object was missing. Parameters header – the header to be removed. to_header() Convert the header set into an HTTP header string. update(iterable) Add all the headers from the iterable to the set. Parameters iterable – updates the set with the items from the iterable.
werkzeug.datastructures.index#werkzeug.datastructures.HeaderSet
add(header) Add a new header to the set.
werkzeug.datastructures.index#werkzeug.datastructures.HeaderSet.add
as_set(preserve_casing=False) Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. Parameters preserve_casing – if set to True the items in the set returned will have the original case like in the HeaderSet, otherwise they will be lowercase.
werkzeug.datastructures.index#werkzeug.datastructures.HeaderSet.as_set
clear() Clear the set.
werkzeug.datastructures.index#werkzeug.datastructures.HeaderSet.clear
discard(header) Like remove() but ignores errors. Parameters header – the header to be discarded.
werkzeug.datastructures.index#werkzeug.datastructures.HeaderSet.discard
find(header) Return the index of the header in the set or return -1 if not found. Parameters header – the header to be looked up.
werkzeug.datastructures.index#werkzeug.datastructures.HeaderSet.find
index(header) Return the index of the header in the set or raise an IndexError. Parameters header – the header to be looked up.
werkzeug.datastructures.index#werkzeug.datastructures.HeaderSet.index
remove(header) Remove a header from the set. This raises an KeyError if the header is not in the set. Changelog Changed in version 0.5: In older versions a IndexError was raised instead of a KeyError if the object was missing. Parameters header – the header to be removed.
werkzeug.datastructures.index#werkzeug.datastructures.HeaderSet.remove
to_header() Convert the header set into an HTTP header string.
werkzeug.datastructures.index#werkzeug.datastructures.HeaderSet.to_header
update(iterable) Add all the headers from the iterable to the set. Parameters iterable – updates the set with the items from the iterable.
werkzeug.datastructures.index#werkzeug.datastructures.HeaderSet.update
class werkzeug.utils.header_property(name, default=None, load_func=None, dump_func=None, read_only=None, doc=None) Like environ_property but for headers.
werkzeug.utils.index#werkzeug.utils.header_property
werkzeug.wsgi.host_is_trusted(hostname, trusted_list) Check if a host matches a list of trusted names. Parameters hostname (str) – The name to check. trusted_list (Iterable[str]) – A list of valid names to match. If a name starts with a dot it will match all subdomains. Return type bool Changelog New in version 0.9.
werkzeug.wsgi.index#werkzeug.wsgi.host_is_trusted
class werkzeug.urls.Href(base='./', charset='utf-8', sort=False, key=None) Implements a callable that constructs URLs with the given base. The function can be called with any number of positional and keyword arguments which than are used to assemble the URL. Works with URLs and posix paths. Positional arguments are appended as individual segments to the path of the URL: >>> href = Href('/foo') >>> href('bar', 23) '/foo/bar/23' >>> href('foo', bar=23) '/foo/foo?bar=23' If any of the arguments (positional or keyword) evaluates to None it will be skipped. If no keyword arguments are given the last argument can be a dict or MultiDict (or any other dict subclass), otherwise the keyword arguments are used for the query parameters, cutting off the first trailing underscore of the parameter name: >>> href(is_=42) '/foo?is=42' >>> href({'foo': 'bar'}) '/foo?foo=bar' Combining of both methods is not allowed: >>> href({'foo': 'bar'}, bar=42) Traceback (most recent call last): ... TypeError: keyword arguments and query-dicts can't be combined Accessing attributes on the href object creates a new href object with the attribute name as prefix: >>> bar_href = href.bar >>> bar_href("blub") '/foo/bar/blub' If sort is set to True the items are sorted by key or the default sorting algorithm: >>> href = Href("/", sort=True) >>> href(a=1, b=2, c=3) '/?a=1&b=2&c=3' Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use werkzeug.routing instead. Changelog New in version 0.5: sort and key were added.
werkzeug.urls.index#werkzeug.urls.Href
class werkzeug.utils.HTMLBuilder(dialect) Helper object for HTML generation. Per default there are two instances of that class. The html one, and the xhtml one for those two dialects. The class uses keyword parameters and positional parameters to generate small snippets of HTML. Keyword parameters are converted to XML/SGML attributes, positional arguments are used as children. Because Python accepts positional arguments before keyword arguments it’s a good idea to use a list with the star-syntax for some children: >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ', ... html.a('bar', href='bar.html')]) '<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>' This class works around some browser limitations and can not be used for arbitrary SGML/XML generation. For that purpose lxml and similar libraries exist. Calling the builder escapes the string passed: >>> html.p(html("<foo>")) '<p>&lt;foo&gt;</p>' Deprecated since version 2.0: Will be removed in Werkzeug 2.1.
werkzeug.utils.index#werkzeug.utils.HTMLBuilder
get_response(environ=None, scope=None) Get a response object. If one was passed to the exception it’s returned directly. Parameters environ (Optional[WSGIEnvironment]) – the optional environ for the request. This can be used to modify the response depending on how the request looked like. scope (Optional[dict]) – Returns a Response object or a subclass thereof. Return type Response
werkzeug.exceptions.index#werkzeug.exceptions.HTTPException.get_response
__call__(environ, start_response) Call the exception as WSGI application. Parameters environ (WSGIEnvironment) – the WSGI environment. start_response (StartResponse) – the response callable provided by the WSGI server. Return type Iterable[bytes]
werkzeug.exceptions.index#werkzeug.exceptions.HTTPException.__call__
werkzeug.http.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. Parameters timestamp (Optional[Union[datetime.datetime, datetime.date, int, float, time.struct_time]]) – The datetime or timestamp to format. Defaults to the current time. Return type str Changed in version 2.0: Use email.utils.format_datetime. Accept date objects.
werkzeug.http.index#werkzeug.http.http_date
class werkzeug.datastructures.IfRange(etag=None, date=None) Very simple object that represents the If-Range header in parsed form. It will either have neither a etag or date or one of either but never both. Changelog New in version 0.7. date The date in parsed format or None. etag The etag parsed and unquoted. Ranges always operate on strong etags so the weakness information is not necessary. to_header() Converts the object back into an HTTP header.
werkzeug.datastructures.index#werkzeug.datastructures.IfRange
date The date in parsed format or None.
werkzeug.datastructures.index#werkzeug.datastructures.IfRange.date
etag The etag parsed and unquoted. Ranges always operate on strong etags so the weakness information is not necessary.
werkzeug.datastructures.index#werkzeug.datastructures.IfRange.etag
to_header() Converts the object back into an HTTP header.
werkzeug.datastructures.index#werkzeug.datastructures.IfRange.to_header
class werkzeug.datastructures.ImmutableDict An immutable dict. Changelog New in version 0.5. copy() Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).
werkzeug.datastructures.index#werkzeug.datastructures.ImmutableDict
copy() Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).
werkzeug.datastructures.index#werkzeug.datastructures.ImmutableDict.copy
class werkzeug.datastructures.ImmutableList(iterable=(), /) An immutable list. Changelog New in version 0.5. Private
werkzeug.datastructures.index#werkzeug.datastructures.ImmutableList
class werkzeug.datastructures.ImmutableMultiDict(mapping=None) An immutable MultiDict. Changelog New in version 0.5. copy() Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).
werkzeug.datastructures.index#werkzeug.datastructures.ImmutableMultiDict
copy() Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).
werkzeug.datastructures.index#werkzeug.datastructures.ImmutableMultiDict.copy
class werkzeug.datastructures.ImmutableOrderedMultiDict(mapping=None) An immutable OrderedMultiDict. Changelog New in version 0.6. copy() Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).
werkzeug.datastructures.index#werkzeug.datastructures.ImmutableOrderedMultiDict
copy() Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).
werkzeug.datastructures.index#werkzeug.datastructures.ImmutableOrderedMultiDict.copy
class werkzeug.datastructures.ImmutableTypeConversionDict Works like a TypeConversionDict but does not support modifications. Changelog New in version 0.5. copy() Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).
werkzeug.datastructures.index#werkzeug.datastructures.ImmutableTypeConversionDict
copy() Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).
werkzeug.datastructures.index#werkzeug.datastructures.ImmutableTypeConversionDict.copy
werkzeug.utils.import_string(import_name, silent=False) Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (xml.sax.saxutils.escape) or with a colon as object delimiter (xml.sax.saxutils:escape). If silent is True the return value will be None if the import fails. Parameters import_name (str) – the dotted name for the object to import. silent (bool) – if set to True import errors are ignored and None is returned instead. Returns imported object Return type Any
werkzeug.utils.index#werkzeug.utils.import_string
Installation Python Version We recommend using the latest version of Python. Werkzeug supports Python 3.6 and newer. Dependencies Werkzeug does not have any direct dependencies. Optional dependencies These distributions will not be installed automatically. Werkzeug will detect and use them if you install them. Colorama provides request log highlighting when using the development server on Windows. This works automatically on other systems. Watchdog provides a faster, more efficient reloader for the development server. Virtual environments Use a virtual environment to manage the dependencies for your project, both in development and in production. What problem does a virtual environment solve? The more Python projects you have, the more likely it is that you need to work with different versions of Python libraries, or even Python itself. Newer versions of libraries for one project can break compatibility in another project. Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system’s packages. Python comes bundled with the venv module to create virtual environments. Create an environment Create a project folder and a venv folder within: mkdir myproject cd myproject python3 -m venv venv On Windows: py -3 -m venv venv Activate the environment Before you work on your project, activate the corresponding environment: . venv/bin/activate On Windows: venv\Scripts\activate Your shell prompt will change to show the name of the activated environment. Install Werkzeug Within the activated environment, use the following command to install Werkzeug: pip install Werkzeug
werkzeug.installation.index
class werkzeug.routing.IntegerConverter(map, fixed_digits=0, min=None, max=None, signed=False) This converter only accepts integer values: Rule("/page/<int:page>") By default it only accepts unsigned, positive values. The signed parameter will enable signed, negative values. Rule("/page/<int(signed=True):page>") Parameters map (Map) – The Map. fixed_digits (int) – The number of fixed digits in the URL. If you set this to 4 for example, the rule will only match if the URL looks like /0001/. The default is variable length. min (Optional[int]) – The minimal value. max (Optional[int]) – The maximal value. signed (bool) – Allow signed (negative) values. Return type None Changelog New in version 0.15: The signed parameter.
werkzeug.routing.index#werkzeug.routing.IntegerConverter
original_exception The original exception that caused this 500 error. Can be used by frameworks to provide context when handling unexpected errors.
werkzeug.exceptions.index#werkzeug.exceptions.InternalServerError.original_exception
werkzeug.utils.invalidate_cached_property(obj, name) Invalidates the cache for a cached_property: >>> class Test(object): ... @cached_property ... def magic_number(self): ... print("recalculating...") ... return 42 ... >>> var = Test() >>> var.magic_number recalculating... 42 >>> var.magic_number 42 >>> invalidate_cached_property(var, "magic_number") >>> var.magic_number recalculating... 42 You must pass the name of the cached property as the second argument. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use del obj.name instead. Parameters obj (object) – name (str) – Return type None
werkzeug.utils.index#werkzeug.utils.invalidate_cached_property
werkzeug.urls.iri_to_uri(iri, charset='utf-8', errors='strict', safe_conversion=False) Convert an IRI to a URI. All non-ASCII and unsafe characters are quoted. If the URL has a domain, it is encoded to Punycode. >>> iri_to_uri('http://\u2603.net/p\xe5th?q=\xe8ry%DF') 'http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF' Parameters iri (Union[str, Tuple[str, str, str, str, str]]) – The IRI to convert. charset (str) – The encoding of the IRI. errors (str) – Error handler to use during bytes.encode. safe_conversion (bool) – Return the URL unchanged if it only contains ASCII characters and no whitespace. See the explanation below. Return type str There is a general problem with IRI conversion with some protocols that are in violation of the URI specification. Consider the following two IRIs: magnet:?xt=uri:whatever itms-services://?action=download-manifest After parsing, we don’t know if the scheme requires the //, which is dropped if empty, but conveys different meanings in the final URL if it’s present or not. In this case, you can use safe_conversion, which will return the URL unchanged if it only contains ASCII characters and no whitespace. This can result in a URI with unquoted characters if it was not already quoted correctly, but preserves the URL’s semantics. Werkzeug uses this for the Location header for redirects. Changelog Changed in version 0.15: All reserved characters remain unquoted. Previously, only some reserved characters were left unquoted. Changed in version 0.9.6: The safe_conversion parameter was added. New in version 0.6.
werkzeug.urls.index#werkzeug.urls.iri_to_uri
werkzeug.http.is_byte_range_valid(start, stop, length) Checks if a given byte content range is valid for the given length. Changelog New in version 0.7. Parameters start (Optional[int]) – stop (Optional[int]) – length (Optional[int]) – Return type bool
werkzeug.http.index#werkzeug.http.is_byte_range_valid
werkzeug.http.is_entity_header(header) Check if a header is an entity header. Changelog New in version 0.5. Parameters header (str) – the header to test. Returns True if it’s an entity header, False otherwise. Return type bool
werkzeug.http.index#werkzeug.http.is_entity_header
werkzeug.http.is_hop_by_hop_header(header) Check if a header is an HTTP/1.1 “Hop-by-Hop” header. Changelog New in version 0.5. Parameters header (str) – the header to test. Returns True if it’s an HTTP/1.1 “Hop-by-Hop” header, False otherwise. Return type bool
werkzeug.http.index#werkzeug.http.is_hop_by_hop_header
werkzeug.http.is_resource_modified(environ, etag=None, data=None, last_modified=None, ignore_if_range=True) Convenience method for conditional requests. Parameters environ (WSGIEnvironment) – the WSGI environment of the request to be checked. etag (Optional[str]) – the etag for the response for comparison. data (Optional[bytes]) – or alternatively the data of the response to automatically generate an etag using generate_etag(). last_modified (Optional[Union[datetime.datetime, str]]) – an optional date of the last modification. ignore_if_range (bool) – If False, If-Range header will be taken into account. Returns True if the resource was modified, otherwise False. Return type bool 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. Changelog Changed in version 1.0.0: The check is run for methods other than GET and HEAD.
werkzeug.http.index#werkzeug.http.is_resource_modified
werkzeug.serving.is_running_from_reloader() Checks if the application is running from within the Werkzeug reloader subprocess. Changelog New in version 0.10. Return type bool
werkzeug.serving.index#werkzeug.serving.is_running_from_reloader
class werkzeug.datastructures.LanguageAccept(values=()) Like Accept but with normalization for language tags.
werkzeug.datastructures.index#werkzeug.datastructures.LanguageAccept
class werkzeug.wsgi.LimitedStream(stream, limit) Wraps a stream so that it doesn’t read more than n bytes. If the stream is exhausted and the caller tries to get more bytes from it on_exhausted() is called which by default returns an empty string. The return value of that function is forwarded to the reader function. So if it returns an empty string read() will return an empty string as well. The limit however must never be higher than what the stream can output. Otherwise readlines() will try to read past the limit. Note on WSGI compliance calls to readline() and readlines() are not WSGI compliant because it passes a size argument to the readline methods. Unfortunately the WSGI PEP is not safely implementable without a size argument to readline() because there is no EOF marker in the stream. As a result of that the use of readline() is discouraged. For the same reason iterating over the LimitedStream is not portable. It internally calls readline(). We strongly suggest using read() only or using the make_line_iter() which safely iterates line-based over a WSGI input stream. Parameters stream (BinaryIO) – the stream to wrap. limit (int) – the limit for the stream, must not be longer than what the string can provide if the stream does not end with EOF (like wsgi.input) Return type None exhaust(chunk_size=65536) Exhaust the stream. This consumes all the data left until the limit is reached. Parameters chunk_size (int) – the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results. Return type None property is_exhausted: bool If the stream is exhausted this attribute is True. on_disconnect() What should happen if a disconnect is detected? The return value of this function is returned from read functions in case the client went away. By default a ClientDisconnected exception is raised. Return type bytes on_exhausted() This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function. Return type bytes read(size=None) Read size bytes or if size is not provided everything is read. Parameters size (Optional[int]) – the number of bytes read. Return type bytes readable() Return whether object was opened for reading. If False, read() will raise OSError. Return type bool readline(size=None) Reads one line from the stream. Parameters size (Optional[int]) – Return type bytes readlines(size=None) Reads a file into a list of strings. It calls readline() until the file is read to the end. It does support the optional size argument if the underlying stream supports it for readline. Parameters size (Optional[int]) – Return type List[bytes] tell() Returns the position of the stream. Changelog New in version 0.9. Return type int
werkzeug.wsgi.index#werkzeug.wsgi.LimitedStream
exhaust(chunk_size=65536) Exhaust the stream. This consumes all the data left until the limit is reached. Parameters chunk_size (int) – the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results. Return type None
werkzeug.wsgi.index#werkzeug.wsgi.LimitedStream.exhaust
on_disconnect() What should happen if a disconnect is detected? The return value of this function is returned from read functions in case the client went away. By default a ClientDisconnected exception is raised. Return type bytes
werkzeug.wsgi.index#werkzeug.wsgi.LimitedStream.on_disconnect
on_exhausted() This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function. Return type bytes
werkzeug.wsgi.index#werkzeug.wsgi.LimitedStream.on_exhausted
read(size=None) Read size bytes or if size is not provided everything is read. Parameters size (Optional[int]) – the number of bytes read. Return type bytes
werkzeug.wsgi.index#werkzeug.wsgi.LimitedStream.read
readable() Return whether object was opened for reading. If False, read() will raise OSError. Return type bool
werkzeug.wsgi.index#werkzeug.wsgi.LimitedStream.readable
readline(size=None) Reads one line from the stream. Parameters size (Optional[int]) – Return type bytes
werkzeug.wsgi.index#werkzeug.wsgi.LimitedStream.readline
readlines(size=None) Reads a file into a list of strings. It calls readline() until the file is read to the end. It does support the optional size argument if the underlying stream supports it for readline. Parameters size (Optional[int]) – Return type List[bytes]
werkzeug.wsgi.index#werkzeug.wsgi.LimitedStream.readlines
tell() Returns the position of the stream. Changelog New in version 0.9. Return type int
werkzeug.wsgi.index#werkzeug.wsgi.LimitedStream.tell
class werkzeug.middleware.lint.LintMiddleware(app) Warns about common errors in the WSGI and HTTP behavior of the server and wrapped application. Some of the issues it checks are: invalid status codes non-bytes sent to the WSGI server strings returned from the WSGI application non-empty conditional responses unquoted etags relative URLs in the Location header unsafe calls to wsgi.input unclosed iterators Error information is emitted using the warnings module. Parameters app (WSGIApplication) – The WSGI application to wrap. Return type None from werkzeug.middleware.lint import LintMiddleware app = LintMiddleware(app)
werkzeug.middleware.lint.index#werkzeug.middleware.lint.LintMiddleware
class werkzeug.local.LocalManager(locals=None, ident_func=None) Local objects cannot manage themselves. For that you need a local manager. You can pass a local manager multiple locals or add them later y appending them to manager.locals. Every time the manager cleans up, it will clean up all the data left in the locals for this context. Changed in version 2.0: ident_func is deprecated and will be removed in Werkzeug 2.1. Changelog Changed in version 0.7: The ident_func parameter was added. Changed in version 0.6.1: The release_local() function can be used instead of a manager. Parameters locals (Optional[Iterable[Union[werkzeug.local.Local, werkzeug.local.LocalStack]]]) – ident_func (None) – Return type None cleanup() Manually clean up the data in the locals for this context. Call this at the end of the request or use make_middleware(). Return type None get_ident() Return the context identifier the local objects use internally for this context. You cannot override this method to change the behavior but use it to link other context local objects (such as SQLAlchemy’s scoped sessions) to the Werkzeug locals. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Changelog Changed in version 0.7: You can pass a different ident function to the local manager that will then be propagated to all the locals passed to the constructor. Return type int make_middleware(app) Wrap a WSGI application so that cleaning up happens after request end. Parameters app (WSGIApplication) – Return type WSGIApplication middleware(func) Like make_middleware but for decorating functions. Example usage: @manager.middleware def application(environ, start_response): ... The difference to make_middleware is that the function passed will have all the arguments copied from the inner application (name, docstring, module). Parameters func (WSGIApplication) – Return type WSGIApplication
werkzeug.local.index#werkzeug.local.LocalManager
cleanup() Manually clean up the data in the locals for this context. Call this at the end of the request or use make_middleware(). Return type None
werkzeug.local.index#werkzeug.local.LocalManager.cleanup
get_ident() Return the context identifier the local objects use internally for this context. You cannot override this method to change the behavior but use it to link other context local objects (such as SQLAlchemy’s scoped sessions) to the Werkzeug locals. Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Changelog Changed in version 0.7: You can pass a different ident function to the local manager that will then be propagated to all the locals passed to the constructor. Return type int
werkzeug.local.index#werkzeug.local.LocalManager.get_ident
make_middleware(app) Wrap a WSGI application so that cleaning up happens after request end. Parameters app (WSGIApplication) – Return type WSGIApplication
werkzeug.local.index#werkzeug.local.LocalManager.make_middleware
middleware(func) Like make_middleware but for decorating functions. Example usage: @manager.middleware def application(environ, start_response): ... The difference to make_middleware is that the function passed will have all the arguments copied from the inner application (name, docstring, module). Parameters func (WSGIApplication) – Return type WSGIApplication
werkzeug.local.index#werkzeug.local.LocalManager.middleware
class werkzeug.local.LocalProxy(local, name=None) A proxy to the object bound to a Local. All operations on the proxy are forwarded to the bound object. If no object is bound, a RuntimeError is raised. from werkzeug.local import Local l = Local() # a proxy to whatever l.user is set to user = l("user") from werkzeug.local import LocalStack _request_stack = LocalStack() # a proxy to _request_stack.top request = _request_stack() # a proxy to the session attribute of the request proxy session = LocalProxy(lambda: request.session) __repr__ and __class__ are forwarded, so repr(x) and isinstance(x, cls) will look like the proxied object. Use issubclass(type(x), LocalProxy) to check if an object is a proxy. repr(user) # <User admin> isinstance(user, User) # True issubclass(type(user), LocalProxy) # True Parameters local – The Local or callable that provides the proxied object. name – The attribute name to look up on a Local. Not used if a callable is given. Changed in version 2.0: Updated proxied attributes and methods to reflect the current data model. Changelog Changed in version 0.6.1: The class can be instantiated with a callable. _get_current_object() Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context. Return type Any
werkzeug.local.index#werkzeug.local.LocalProxy
_get_current_object() Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context. Return type Any
werkzeug.local.index#werkzeug.local.LocalProxy._get_current_object
class werkzeug.local.LocalStack This class works similar to a Local but keeps a stack of objects instead. This is best explained with an example: >>> ls = LocalStack() >>> ls.push(42) >>> ls.top 42 >>> ls.push(23) >>> ls.top 23 >>> ls.pop() 23 >>> ls.top 42 They can be force released by using a LocalManager or with the release_local() function but the correct way is to pop the item from the stack after using. When the stack is empty it will no longer be bound to the current context (and as such released). By calling the stack without arguments it returns a proxy that resolves to the topmost item on the stack. Changelog New in version 0.6.1. Return type None pop() Removes the topmost item from the stack, will return the old value or None if the stack was already empty. Return type Any push(obj) Pushes a new item to the stack Parameters obj (Any) – Return type List[Any] property top: Any The topmost item on the stack. If the stack is empty, None is returned.
werkzeug.local.index#werkzeug.local.LocalStack
pop() Removes the topmost item from the stack, will return the old value or None if the stack was already empty. Return type Any
werkzeug.local.index#werkzeug.local.LocalStack.pop
push(obj) Pushes a new item to the stack Parameters obj (Any) – Return type List[Any]
werkzeug.local.index#werkzeug.local.LocalStack.push
werkzeug.wsgi.make_chunk_iter(stream, separator, limit=None, buffer_size=10240, cap_at_buffer=False) Works like make_line_iter() but accepts a separator which divides chunks. If you want newline based processing you should use make_line_iter() instead as it supports arbitrary newline markers. Changelog New in version 0.11.10: added support for the cap_at_buffer parameter. New in version 0.9: added support for iterators as input stream. New in version 0.8. Parameters stream (Union[Iterable[bytes], BinaryIO]) – the stream or iterate to iterate over. separator (bytes) – the separator that divides chunks. limit (Optional[int]) – the limit in bytes for the stream. (Usually content length. Not necessary if the stream is otherwise already limited). buffer_size (int) – The optional buffer size. cap_at_buffer (bool) – if this is set chunks are split if they are longer than the buffer size. Internally this is implemented that the buffer size might be exhausted by a factor of two however. Return type Iterator[bytes]
werkzeug.wsgi.index#werkzeug.wsgi.make_chunk_iter
werkzeug.wsgi.make_line_iter(stream, limit=None, buffer_size=10240, cap_at_buffer=False) Safely iterates line-based over an input stream. If the input stream is not a LimitedStream the limit parameter is mandatory. This uses the stream’s read() method internally as opposite to the readline() method that is unsafe and can only be used in violation of the WSGI specification. The same problem applies to the __iter__ function of the input stream which calls readline() without arguments. If you need line-by-line processing it’s strongly recommended to iterate over the input stream using this helper function. Changelog New in version 0.11.10: added support for the cap_at_buffer parameter. New in version 0.9: added support for iterators as input stream. Changed in version 0.8: This function now ensures that the limit was reached. Parameters stream (Union[Iterable[bytes], BinaryIO]) – the stream or iterate to iterate over. limit (Optional[int]) – the limit in bytes for the stream. (Usually content length. Not necessary if the stream is a LimitedStream. buffer_size (int) – The optional buffer size. cap_at_buffer (bool) – if this is set chunks are split if they are longer than the buffer size. Internally this is implemented that the buffer size might be exhausted by a factor of two however. Return type Iterator[bytes]
werkzeug.wsgi.index#werkzeug.wsgi.make_line_iter
werkzeug.serving.make_ssl_devcert(base_path, host=None, cn=None) Creates an SSL key for development. This should be used instead of the 'adhoc' key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it will use the CN *.host/CN=host. For more information see run_simple(). Changelog New in version 0.9. Parameters base_path (str) – the path to the certificate and key. The extension .crt is added for the certificate, .key is added for the key. host (Optional[str]) – the name of the host. This can be used as an alternative for the cn. cn (Optional[str]) – the CN to use. Return type Tuple[str, str]
werkzeug.serving.index#werkzeug.serving.make_ssl_devcert
class werkzeug.routing.Map(rules=None, default_subdomain='', charset='utf-8', strict_slashes=True, merge_slashes=True, redirect_defaults=True, converters=None, sort_parameters=False, sort_key=None, encoding_errors='replace', host_matching=False) The map class stores all the URL rules and some configuration parameters. Some of the configuration values are only stored on the Map instance since those affect all rules, others are just defaults and can be overridden for each rule. Note that you have to specify all arguments besides the rules as keyword arguments! Parameters rules (Optional[Iterable[werkzeug.routing.RuleFactory]]) – sequence of url rules for this map. default_subdomain (str) – The default subdomain for rules without a subdomain defined. charset (str) – charset of the url. defaults to "utf-8" strict_slashes (bool) – If a rule ends with a slash but the matched URL does not, redirect to the URL with a trailing slash. merge_slashes (bool) – Merge consecutive slashes when matching or building URLs. Matches will redirect to the normalized URL. Slashes in variable parts are not merged. redirect_defaults (bool) – This will redirect to the default rule if it wasn’t visited that way. This helps creating unique URLs. converters (Optional[Mapping[str, Type[werkzeug.routing.BaseConverter]]]) – A dict of converters that adds additional converters to the list of converters. If you redefine one converter this will override the original one. sort_parameters (bool) – If set to True the url parameters are sorted. See url_encode for more details. sort_key (Optional[Callable[[Any], Any]]) – The sort key function for url_encode. encoding_errors (str) – the error method to use for decoding host_matching (bool) – if set to True it enables the host matching feature and disables the subdomain one. If enabled the host parameter to rules is used instead of the subdomain one. Return type None Changelog Changed in version 1.0: If url_scheme is ws or wss, only WebSocket rules will match. Changed in version 1.0: Added merge_slashes. Changed in version 0.7: Added encoding_errors and host_matching. Changed in version 0.5: Added sort_parameters and sort_key. converters The dictionary of converters. This can be modified after the class was created, but will only affect rules added after the modification. If the rules are defined with the list passed to the class, the converters parameter to the constructor has to be used instead. add(rulefactory) Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map. Parameters rulefactory (werkzeug.routing.RuleFactory) – a Rule or RuleFactory Return type None bind(server_name, script_name=None, subdomain=None, url_scheme='http', default_method='GET', path_info=None, query_args=None) Return a new MapAdapter with the details specified to the call. Note that script_name will default to '/' if not further specified or None. The server_name at least is a requirement because the HTTP RFC requires absolute URLs for redirects and so all redirect exceptions raised by Werkzeug will contain the full canonical URL. If no path_info is passed to match() it will use the default path info passed to bind. While this doesn’t really make sense for manual bind calls, it’s useful if you bind a map to a WSGI environment which already contains the path info. subdomain will default to the default_subdomain for this map if no defined. If there is no default_subdomain you cannot use the subdomain feature. Changelog Changed in version 1.0: If url_scheme is ws or wss, only WebSocket rules will match. Changed in version 0.15: path_info defaults to '/' if None. Changed in version 0.8: query_args can be a string. Changed in version 0.7: Added query_args. Parameters server_name (str) – script_name (Optional[str]) – subdomain (Optional[str]) – url_scheme (str) – default_method (str) – path_info (Optional[str]) – query_args (Optional[Union[Mapping[str, Any], str]]) – Return type werkzeug.routing.MapAdapter bind_to_environ(environ, server_name=None, subdomain=None) Like bind() but you can pass it an WSGI environment and it will fetch the information from that dictionary. Note that because of limitations in the protocol there is no way to get the current subdomain and real server_name from the environment. If you don’t provide it, Werkzeug will use SERVER_NAME and SERVER_PORT (or HTTP_HOST if provided) as used server_name with disabled subdomain feature. If subdomain is None but an environment and a server name is provided it will calculate the current subdomain automatically. Example: server_name is 'example.com' and the SERVER_NAME in the wsgi environ is 'staging.dev.example.com' the calculated subdomain will be 'staging.dev'. If the object passed as environ has an environ attribute, the value of this attribute is used instead. This allows you to pass request objects. Additionally PATH_INFO added as a default of the MapAdapter so that you don’t have to pass the path info to the match method. Changelog Changed in version 1.0.0: If the passed server name specifies port 443, it will match if the incoming scheme is https without a port. Changed in version 1.0.0: A warning is shown when the passed server name does not match the incoming WSGI server name. Changed in version 0.8: This will no longer raise a ValueError when an unexpected server name was passed. Changed in version 0.5: previously this method accepted a bogus calculate_subdomain parameter that did not have any effect. It was removed because of that. Parameters environ (WSGIEnvironment) – a WSGI environment. server_name (Optional[str]) – an optional server name hint (see above). subdomain (Optional[str]) – optionally the current subdomain (see above). Return type MapAdapter default_converters = {'any': <class 'werkzeug.routing.AnyConverter'>, 'default': <class 'werkzeug.routing.UnicodeConverter'>, 'float': <class 'werkzeug.routing.FloatConverter'>, 'int': <class 'werkzeug.routing.IntegerConverter'>, 'path': <class 'werkzeug.routing.PathConverter'>, 'string': <class 'werkzeug.routing.UnicodeConverter'>, 'uuid': <class 'werkzeug.routing.UUIDConverter'>} A dict of default converters to be used. is_endpoint_expecting(endpoint, *arguments) Iterate over all rules and check if the endpoint expects the arguments provided. This is for example useful if you have some URLs that expect a language code and others that do not and you want to wrap the builder a bit so that the current language code is automatically added if not provided but endpoints expect it. Parameters endpoint (str) – the endpoint to check. arguments (str) – this function accepts one or more arguments as positional arguments. Each one of them is checked. Return type bool iter_rules(endpoint=None) Iterate over all rules or the rules of an endpoint. Parameters endpoint (Optional[str]) – if provided only the rules for that endpoint are returned. Returns an iterator Return type Iterator[werkzeug.routing.Rule] lock_class() The type of lock to use when updating. Changelog New in version 1.0. update() Called before matching and building to keep the compiled rules in the correct order after things changed. Return type None
werkzeug.routing.index#werkzeug.routing.Map
add(rulefactory) Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map. Parameters rulefactory (werkzeug.routing.RuleFactory) – a Rule or RuleFactory Return type None
werkzeug.routing.index#werkzeug.routing.Map.add
bind(server_name, script_name=None, subdomain=None, url_scheme='http', default_method='GET', path_info=None, query_args=None) Return a new MapAdapter with the details specified to the call. Note that script_name will default to '/' if not further specified or None. The server_name at least is a requirement because the HTTP RFC requires absolute URLs for redirects and so all redirect exceptions raised by Werkzeug will contain the full canonical URL. If no path_info is passed to match() it will use the default path info passed to bind. While this doesn’t really make sense for manual bind calls, it’s useful if you bind a map to a WSGI environment which already contains the path info. subdomain will default to the default_subdomain for this map if no defined. If there is no default_subdomain you cannot use the subdomain feature. Changelog Changed in version 1.0: If url_scheme is ws or wss, only WebSocket rules will match. Changed in version 0.15: path_info defaults to '/' if None. Changed in version 0.8: query_args can be a string. Changed in version 0.7: Added query_args. Parameters server_name (str) – script_name (Optional[str]) – subdomain (Optional[str]) – url_scheme (str) – default_method (str) – path_info (Optional[str]) – query_args (Optional[Union[Mapping[str, Any], str]]) – Return type werkzeug.routing.MapAdapter
werkzeug.routing.index#werkzeug.routing.Map.bind
bind_to_environ(environ, server_name=None, subdomain=None) Like bind() but you can pass it an WSGI environment and it will fetch the information from that dictionary. Note that because of limitations in the protocol there is no way to get the current subdomain and real server_name from the environment. If you don’t provide it, Werkzeug will use SERVER_NAME and SERVER_PORT (or HTTP_HOST if provided) as used server_name with disabled subdomain feature. If subdomain is None but an environment and a server name is provided it will calculate the current subdomain automatically. Example: server_name is 'example.com' and the SERVER_NAME in the wsgi environ is 'staging.dev.example.com' the calculated subdomain will be 'staging.dev'. If the object passed as environ has an environ attribute, the value of this attribute is used instead. This allows you to pass request objects. Additionally PATH_INFO added as a default of the MapAdapter so that you don’t have to pass the path info to the match method. Changelog Changed in version 1.0.0: If the passed server name specifies port 443, it will match if the incoming scheme is https without a port. Changed in version 1.0.0: A warning is shown when the passed server name does not match the incoming WSGI server name. Changed in version 0.8: This will no longer raise a ValueError when an unexpected server name was passed. Changed in version 0.5: previously this method accepted a bogus calculate_subdomain parameter that did not have any effect. It was removed because of that. Parameters environ (WSGIEnvironment) – a WSGI environment. server_name (Optional[str]) – an optional server name hint (see above). subdomain (Optional[str]) – optionally the current subdomain (see above). Return type MapAdapter
werkzeug.routing.index#werkzeug.routing.Map.bind_to_environ
converters The dictionary of converters. This can be modified after the class was created, but will only affect rules added after the modification. If the rules are defined with the list passed to the class, the converters parameter to the constructor has to be used instead.
werkzeug.routing.index#werkzeug.routing.Map.converters
default_converters = {'any': <class 'werkzeug.routing.AnyConverter'>, 'default': <class 'werkzeug.routing.UnicodeConverter'>, 'float': <class 'werkzeug.routing.FloatConverter'>, 'int': <class 'werkzeug.routing.IntegerConverter'>, 'path': <class 'werkzeug.routing.PathConverter'>, 'string': <class 'werkzeug.routing.UnicodeConverter'>, 'uuid': <class 'werkzeug.routing.UUIDConverter'>} A dict of default converters to be used.
werkzeug.routing.index#werkzeug.routing.Map.default_converters
is_endpoint_expecting(endpoint, *arguments) Iterate over all rules and check if the endpoint expects the arguments provided. This is for example useful if you have some URLs that expect a language code and others that do not and you want to wrap the builder a bit so that the current language code is automatically added if not provided but endpoints expect it. Parameters endpoint (str) – the endpoint to check. arguments (str) – this function accepts one or more arguments as positional arguments. Each one of them is checked. Return type bool
werkzeug.routing.index#werkzeug.routing.Map.is_endpoint_expecting
iter_rules(endpoint=None) Iterate over all rules or the rules of an endpoint. Parameters endpoint (Optional[str]) – if provided only the rules for that endpoint are returned. Returns an iterator Return type Iterator[werkzeug.routing.Rule]
werkzeug.routing.index#werkzeug.routing.Map.iter_rules
lock_class() The type of lock to use when updating. Changelog New in version 1.0.
werkzeug.routing.index#werkzeug.routing.Map.lock_class
update() Called before matching and building to keep the compiled rules in the correct order after things changed. Return type None
werkzeug.routing.index#werkzeug.routing.Map.update