to_uri_tuple()
Returns a BytesURL tuple that holds a URI. This will encode all the information in the URL properly to ASCII using the rules a web browser would follow. It’s usually more interesting to directly call iri_to_uri() which will return a string.  Return type
werkzeug.urls.BaseURL


to_url()
Returns a URL string or bytes depending on the type of the information stored. This is just a convenience function for calling url_unparse() for this URL.  Return type
str


werkzeug.utils.bind_arguments(func, args, kwargs)
Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments bind_arguments returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments.  Parameters

func – the function the arguments should be bound for.
args – tuple of positional arguments.
kwargs – a dict of keyword arguments.   Returns
a dict of bound keyword arguments.    Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use Signature.bind() instead.


class werkzeug.filesystem.BrokenFilesystemWarning
The warning used by Werkzeug to signal a broken filesystem. Will only be used once per runtime.


class werkzeug.urls.BytesURL(scheme, netloc, path, query, fragment)
Represents a parsed URL in bytes. Create new instance of _URLTuple(scheme, netloc, path, query, fragment)  Parameters

scheme (str) –
netloc (str) –
path (str) –
query (str) –
fragment (str) –
decode(charset='utf-8', errors='replace')
Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment.  Parameters

charset (str) –
errors (str) –    Return type
werkzeug.urls.URL

encode_netloc()
Returns the netloc unchanged as bytes.  Return type
bytes


decode(charset='utf-8', errors='replace')
Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment.  Parameters

charset (str) –
errors (str) –    Return type
werkzeug.urls.URL


encode_netloc()
Returns the netloc unchanged as bytes.  Return type
bytes


class werkzeug.utils.cached_property(fget, name=None, doc=None)
A property() that is only evaluated once. Subsequent access returns the cached value. Setting the property sets the cached value. Deleting the property clears the cached value, accessing it again will evaluate it again. class Example:
    @cached_property
    def value(self):
        # calculate something important here
        return 42

e = Example()
e.value  # evaluates
e.value  # uses cache
e.value = 16  # sets cache
del e.value  # clears cache
 The class must have a __dict__ for this to work.  Changed in version 2.0: del obj.name clears the cached value.   Parameters

fget (Callable[[Any], Any]) –
name (Optional[str]) –
doc (Optional[str]) –    Return type
None


CGI If all other deployment methods do not work, CGI will work for sure. CGI is supported by all major servers but usually has a less-than-optimal performance. This is also the way you can use a Werkzeug application on Google’s AppEngine, there however the execution does happen in a CGI-like environment. The application’s performance is unaffected because of that.  Creating a .cgi file First you need to create the CGI application file. Let’s call it yourapplication.cgi: #!/usr/bin/python
from wsgiref.handlers import CGIHandler
from yourapplication import make_app

application = make_app()
CGIHandler().run(application)
   Server Setup Usually there are two ways to configure the server. Either just copy the .cgi into a cgi-bin (and use mod_rewrite or something similar to rewrite the URL) or let the server point to the file directly. In Apache for example you can put something like this into the config: ScriptAlias /app /path/to/the/application.cgi
 For more information consult the documentation of your webserver.


class werkzeug.datastructures.CharsetAccept(values=())
Like Accept but with normalization for charsets.


werkzeug.security.check_password_hash(pwhash, password)
Check a password against a given salted and hashed password value. In order to support unsalted legacy passwords this method supports plain text passwords, md5 and sha1 hashes (both salted and unsalted). Returns True if the password matched, False otherwise.  Parameters

pwhash (str) – a hashed string like returned by generate_password_hash().
password (str) – the plaintext password to compare against the hash.   Return type
bool


class werkzeug.test.Client(application, response_wrapper=None, use_cookies=True, allow_subdomain_redirects=False)
This class allows you to send requests to a wrapped application. The use_cookies parameter indicates whether cookies should be stored and sent for subsequent requests. This is True by default, but passing False will disable this behaviour. If you want to request some subdomain of your application you may set allow_subdomain_redirects to True as if not no external redirects are allowed.  Changed in version 2.0: response_wrapper is always a subclass of :class:TestResponse.   Changelog Changed in version 0.5: Added the use_cookies parameter.   Parameters

application (WSGIApplication) –
response_wrapper (Optional[Type[Response]]) –
use_cookies (bool) –
allow_subdomain_redirects (bool) –    Return type
None
set_cookie(server_name, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None, charset='utf-8')
Sets a cookie in the client’s cookie jar. The server name is required and has to match the one that is also passed to the open call.  Parameters

server_name (str) –
key (str) –
value (str) –
max_age (Optional[Union[datetime.timedelta, int]]) –
expires (Optional[Union[str, datetime.datetime, int, float]]) –
path (str) –
domain (Optional[str]) –
secure (bool) –
httponly (bool) –
samesite (Optional[str]) –
charset (str) –    Return type
None

delete_cookie(server_name, key, path='/', domain=None, secure=False, httponly=False, samesite=None)
Deletes a cookie in the test client.  Parameters

server_name (str) –
key (str) –
path (str) –
domain (Optional[str]) –
secure (bool) –
httponly (bool) –
samesite (Optional[str]) –    Return type
None

open(*args, as_tuple=False, buffered=False, follow_redirects=False, **kwargs)
Generate an environ dict from the given arguments, make a request to the application using it, and return the response.  Parameters

args (Any) – Passed to EnvironBuilder to create the environ for the request. If a single arg is passed, it can be an existing EnvironBuilder or an environ dict.
buffered (bool) – Convert the iterator returned by the app into a list. If the iterator has a close() method, it is called automatically.
follow_redirects (bool) – Make additional requests to follow HTTP redirects until a non-redirect status is returned. TestResponse.history lists the intermediate responses.
as_tuple (bool) –
kwargs (Any) –    Return type
werkzeug.test.TestResponse    Changed in version 2.0: as_tuple is deprecated and will be removed in Werkzeug 2.1. Use TestResponse.request and request.environ instead.   Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed.   Changelog Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper.   Changed in version 0.5: Added the follow_redirects parameter.

get(*args, **kw)
Call open() with method set to GET.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse

post(*args, **kw)
Call open() with method set to POST.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse

put(*args, **kw)
Call open() with method set to PUT.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse

delete(*args, **kw)
Call open() with method set to DELETE.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse

patch(*args, **kw)
Call open() with method set to PATCH.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse

options(*args, **kw)
Call open() with method set to OPTIONS.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse

head(*args, **kw)
Call open() with method set to HEAD.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse

trace(*args, **kw)
Call open() with method set to TRACE.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse


delete(*args, **kw)
Call open() with method set to DELETE.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse


delete_cookie(server_name, key, path='/', domain=None, secure=False, httponly=False, samesite=None)
Deletes a cookie in the test client.  Parameters

server_name (str) –
key (str) –
path (str) –
domain (Optional[str]) –
secure (bool) –
httponly (bool) –
samesite (Optional[str]) –    Return type
None


get(*args, **kw)
Call open() with method set to GET.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse


head(*args, **kw)
Call open() with method set to HEAD.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse


open(*args, as_tuple=False, buffered=False, follow_redirects=False, **kwargs)
Generate an environ dict from the given arguments, make a request to the application using it, and return the response.  Parameters

args (Any) – Passed to EnvironBuilder to create the environ for the request. If a single arg is passed, it can be an existing EnvironBuilder or an environ dict.
buffered (bool) – Convert the iterator returned by the app into a list. If the iterator has a close() method, it is called automatically.
follow_redirects (bool) – Make additional requests to follow HTTP redirects until a non-redirect status is returned. TestResponse.history lists the intermediate responses.
as_tuple (bool) –
kwargs (Any) –    Return type
werkzeug.test.TestResponse    Changed in version 2.0: as_tuple is deprecated and will be removed in Werkzeug 2.1. Use TestResponse.request and request.environ instead.   Changed in version 2.0: The request input stream is closed when calling response.close(). Input streams for redirects are automatically closed.   Changelog Changed in version 0.5: If a dict is provided as file in the dict for the data parameter the content type has to be called content_type instead of mimetype. This change was made for consistency with werkzeug.FileWrapper.   Changed in version 0.5: Added the follow_redirects parameter.


options(*args, **kw)
Call open() with method set to OPTIONS.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse


patch(*args, **kw)
Call open() with method set to PATCH.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse


post(*args, **kw)
Call open() with method set to POST.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse


put(*args, **kw)
Call open() with method set to PUT.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse


set_cookie(server_name, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None, charset='utf-8')
Sets a cookie in the client’s cookie jar. The server name is required and has to match the one that is also passed to the open call.  Parameters

server_name (str) –
key (str) –
value (str) –
max_age (Optional[Union[datetime.timedelta, int]]) –
expires (Optional[Union[str, datetime.datetime, int, float]]) –
path (str) –
domain (Optional[str]) –
secure (bool) –
httponly (bool) –
samesite (Optional[str]) –
charset (str) –    Return type
None


trace(*args, **kw)
Call open() with method set to TRACE.  Parameters

args (Any) –
kw (Any) –    Return type
werkzeug.test.TestResponse


class werkzeug.wsgi.ClosingIterator(iterable, callbacks=None)
The WSGI specification requires that all middlewares and gateways respect the close callback of the iterable returned by the application. Because it is useful to add another close action to a returned iterable and adding a custom iterable is a boring task this class can be used for that: return ClosingIterator(app(environ, start_response), [cleanup_session,
                                                      cleanup_locals])
 If there is just one close function it can be passed instead of the list. A closing iterator is not needed if the application uses response objects and finishes the processing if the response is started: try:
    return response(environ, start_response)
finally:
    cleanup_session()
    cleanup_locals()
  Parameters

iterable (Iterable[bytes]) –
callbacks (Optional[Union[Callable[[], None], Iterable[Callable[[], None]]]]) –    Return type
None


class werkzeug.datastructures.CombinedMultiDict(dicts=None)
A read only MultiDict that you can pass multiple MultiDict instances as sequence and it will combine the return values of all wrapped dicts: >>> from werkzeug.datastructures import CombinedMultiDict, MultiDict
>>> post = MultiDict([('foo', 'bar')])
>>> get = MultiDict([('blub', 'blah')])
>>> combined = CombinedMultiDict([get, post])
>>> combined['foo']
'bar'
>>> combined['blub']
'blah'
 This works for all read operations and will raise a TypeError for methods that usually change data which isn’t possible. 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.


class werkzeug.datastructures.ContentRange(units, start, stop, length=None, on_update=None)
Represents the content range header.  Changelog New in version 0.7.
property length
The length of the range or None.

set(start, stop, length=None, units='bytes')
Simple method to update the ranges.

property start
The start point of the range or None.

property stop
The stop point of the range (non-inclusive) or None. Can only be None if also start is None.

property units
The units to use, usually “bytes”

unset()
Sets the units to None which indicates that the header should no longer be used.


set(start, stop, length=None, units='bytes')
Simple method to update the ranges.


unset()
Sets the units to None which indicates that the header should no longer be used.


werkzeug.http.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 (Optional[Union[datetime.datetime, datetime.date, int, float, time.struct_time]]) –   Return type
str


werkzeug.test.create_environ(*args, **kwargs)
Create a new WSGI environ dict based on the values passed. The first parameter should be the path of the request which defaults to ‘/’. The second one can either be an absolute path (in that case the host is localhost:80) or a full path to the request with scheme, netloc port and the path to the script. This accepts the same arguments as the EnvironBuilder constructor.  Changelog Changed in version 0.5: This function is now a thin wrapper over EnvironBuilder which was added in 0.5. The headers, environ_base, environ_overrides and charset parameters were added.   Parameters

args (Any) –
kwargs (Any) –    Return type
WSGIEnvironment


class werkzeug.debug.DebuggedApplication(app, evalex=False, request_key='werkzeug.request', console_path='/console', console_init_func=None, show_hidden_frames=False, pin_security=True, pin_logging=True)
Enables debugging support for a given application: from werkzeug.debug import DebuggedApplication
from myapp import app
app = DebuggedApplication(app, evalex=True)
 The evalex keyword argument allows evaluating expressions in a traceback’s frame context.  Parameters

app (WSGIApplication) – the WSGI application to run debugged.
evalex (bool) – enable exception evaluation feature (interactive debugging). This requires a non-forking server.
request_key (str) – The key that points to the request object in ths environment. This parameter is ignored in current versions.
console_path (str) – the URL for a general purpose console.
console_init_func (Optional[Callable[[], Dict[str, Any]]]) – the function that is executed before starting the general purpose console. The return value is used as initial namespace.
show_hidden_frames (bool) – by default hidden traceback frames are skipped. You can show them by setting this parameter to True.
pin_security (bool) – can be used to disable the pin based security system.
pin_logging (bool) – enables the logging of the pin system.   Return type
None


class werkzeug.middleware.dispatcher.DispatcherMiddleware(app, mounts=None)
Combine multiple applications as a single WSGI application. Requests are dispatched to an application based on the path it is mounted under.  Parameters

app (WSGIApplication) – The WSGI application to dispatch to if the request doesn’t match a mounted path.
mounts (Optional[Dict[str, WSGIApplication]]) – Maps path prefixes to applications for dispatching.   Return type
None


werkzeug.http.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.  Parameters

max_age (Optional[Union[datetime.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 (Optional[Union[str, datetime.datetime, int, float]]) – should be a datetime object or unix timestamp.
path (Optional[str]) – limits the cookie to a given path, per default it will span the whole domain.
domain (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 (bool) – The cookie will only be available via HTTPS
httponly (bool) – disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers.
charset (str) – the encoding for string values.
sync_expires (bool) – automatically set expires if max_age is defined but expires not.
max_size (int) – Warn 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 (Optional[str]) – Limits the scope of the cookie such that it will only be attached to requests if those requests are same-site.
key (str) –
value (Union[bytes, str]) –    Return type
str    Changelog Changed in version 1.0.0: The string 'None' is accepted for samesite.


werkzeug.http.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 (Union[Dict[str, Union[str, int]], Iterable[str]]) – the iterable or dict of values to quote.
allow_token (bool) – if set to False tokens as values are disallowed. See quote_header_value() for more details.   Return type
str


class werkzeug.routing.EndpointPrefix(prefix, rules)
Prefixes all endpoints (which must be strings for this factory) with another string. This can be useful for sub applications: url_map = Map([
    Rule('/', endpoint='index'),
    EndpointPrefix('blog/', [Submount('/blog', [
        Rule('/', endpoint='index'),
        Rule('/entry/<entry_slug>', endpoint='show')
    ])])
])
  Parameters

prefix (str) –
rules (Iterable[Rule]) –    Return type
None


class werkzeug.test.EnvironBuilder(path='/', base_url=None, query_string=None, method='GET', input_stream=None, content_type=None, content_length=None, errors_stream=None, multithread=False, multiprocess=False, run_once=False, headers=None, data=None, environ_base=None, environ_overrides=None, charset='utf-8', mimetype=None, json=None, auth=None)
This class can be used to conveniently create a WSGI environment for testing purposes. It can be used to quickly create WSGI environments or request objects from arbitrary data. The signature of this class is also used in some other places as of Werkzeug 0.5 (create_environ(), Response.from_values(), Client.open()). Because of this most of the functionality is available through the constructor alone. Files and regular form data can be manipulated independently of each other with the form and files attributes, but are passed with the same argument to the constructor: data. data can be any of these values:  a str or bytes object: The object is converted into an input_stream, the content_length is set and you have to provide a content_type.
a dict or MultiDict: The keys have to be strings. The values have to be either any of the following objects, or a list of any of the following objects:  a file-like object: These are converted into FileStorage objects automatically. a tuple: The add_file() method is called with the key and the unpacked tuple items as positional arguments. a str: The string is set as form data for the associated key.   a file-like object: The object content is loaded in memory and then handled like a regular str or a bytes.   Parameters

path (str) – the path of the request. In the WSGI environment this will end up as PATH_INFO. If the query_string is not defined and there is a question mark in the path everything after it is used as query string.
base_url (Optional[str]) – the base URL is a URL that is used to extract the WSGI URL scheme, host (server name + server port) and the script root (SCRIPT_NAME).
query_string (Optional[Union[Mapping[str, str], str]]) – an optional string or dict with URL parameters.
method (str) – the HTTP method to use, defaults to GET.
input_stream (Optional[BinaryIO]) – an optional input stream. Do not specify this and data. As soon as an input stream is set you can’t modify args and files unless you set the input_stream to None again.
content_type (Optional[str]) – The content type for the request. As of 0.5 you don’t have to provide this when specifying files and form data via data.
content_length (Optional[int]) – The content length for the request. You don’t have to specify this when providing data via data.
errors_stream (Optional[TextIO]) – an optional error stream that is used for wsgi.errors. Defaults to stderr.
multithread (bool) – controls wsgi.multithread. Defaults to False.
multiprocess (bool) – controls wsgi.multiprocess. Defaults to False.
run_once (bool) – controls wsgi.run_once. Defaults to False.
headers (Optional[Union[werkzeug.datastructures.Headers, Iterable[Tuple[str, str]]]]) – an optional list or Headers object of headers.
data (Optional[Union[BinaryIO, str, bytes, Mapping[str, Any]]]) – a string or dict of form data or a file-object. See explanation above.
json (Optional[Mapping[str, Any]]) – An object to be serialized and assigned to data. Defaults the content type to "application/json". Serialized with the function assigned to json_dumps.
environ_base (Optional[Mapping[str, Any]]) – an optional dict of environment defaults.
environ_overrides (Optional[Mapping[str, Any]]) – an optional dict of environment overrides.
charset (str) – the charset used to encode string data.
auth (Optional[Union[werkzeug.datastructures.Authorization, Tuple[str, str]]]) – An authorization object to use for the Authorization header value. A (username, password) tuple is a shortcut for Basic authorization.
mimetype (Optional[str]) –    Return type
None    Changed in version 2.0: REQUEST_URI and RAW_URI is the full raw URI including the query string, not only the path.   Changed in version 2.0: The default request_class is Request instead of BaseRequest.   New in version 2.0: Added the auth parameter.   Changelog New in version 0.15: The json param and json_dumps() method.   New in version 0.15: The environ has keys REQUEST_URI and RAW_URI containing the path before perecent-decoding. This is not part of the WSGI PEP, but many WSGI servers include it.   Changed in version 0.6: path and base_url can now be unicode strings that are encoded with iri_to_uri().
server_protocol = 'HTTP/1.1'
the server protocol to use. defaults to HTTP/1.1

wsgi_version = (1, 0)
the wsgi version to use. defaults to (1, 0)

request_class
alias of werkzeug.wrappers.request.Request

static json_dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
The serialization function used when json is passed.

classmethod from_environ(environ, **kwargs)
Turn an environ dict back into a builder. Any extra kwargs override the args extracted from the environ.  Changed in version 2.0: Path and query values are passed through the WSGI decoding dance to avoid double encoding.   Changelog New in version 0.15.   Parameters

environ (WSGIEnvironment) –
kwargs (Any) –    Return type
EnvironBuilder

property base_url: str
The base URL is used to extract the URL scheme, host name, port, and root path.

property content_type: Optional[str]
The content type for the request. Reflected from and to the headers. Do not set if you set files or form for auto detection.

property mimetype: Optional[str]
The mimetype (content type without charset etc.)  Changelog New in version 0.14.

property mimetype_params: Mapping[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.14.

property content_length: Optional[int]
The content length as integer. Reflected from and to the headers. Do not set if you set files or form for auto detection.

property form: werkzeug.datastructures.MultiDict
A MultiDict of form values.

property files: werkzeug.datastructures.FileMultiDict
A FileMultiDict of uploaded files. Use add_file() to add new files.

property input_stream: Optional[BinaryIO]
An optional input stream. This is mutually exclusive with setting form and files, setting it will clear those. Do not provide this if the method is not POST or another method that has a body.

property query_string: str
The query string. If you set this to a string args will no longer be available.

property args: werkzeug.datastructures.MultiDict
The URL arguments as MultiDict.

property server_name: str
The server name (read-only, use host to set)

property server_port: int
The server port as integer (read-only, use host to set)

close()
Closes all files. If you put real file objects into the files dict you can call this method to automatically close them all in one go.  Return type
None

get_environ()
Return the built environ.  Changelog Changed in version 0.15: The content type and length headers are set based on input stream detection. Previously this only set the WSGI keys.   Return type
WSGIEnvironment

get_request(cls=None)
Returns a request with the data. If the request class is not specified request_class is used.  Parameters
cls (Optional[Type[werkzeug.wrappers.request.Request]]) – The request wrapper to use.  Return type
werkzeug.wrappers.request.Request


close()
Closes all files. If you put real file objects into the files dict you can call this method to automatically close them all in one go.  Return type
None


classmethod from_environ(environ, **kwargs)
Turn an environ dict back into a builder. Any extra kwargs override the args extracted from the environ.  Changed in version 2.0: Path and query values are passed through the WSGI decoding dance to avoid double encoding.   Changelog New in version 0.15.   Parameters

environ (WSGIEnvironment) –
kwargs (Any) –    Return type
EnvironBuilder


get_environ()
Return the built environ.  Changelog Changed in version 0.15: The content type and length headers are set based on input stream detection. Previously this only set the WSGI keys.   Return type
WSGIEnvironment


get_request(cls=None)
Returns a request with the data. If the request class is not specified request_class is used.  Parameters
cls (Optional[Type[werkzeug.wrappers.request.Request]]) – The request wrapper to use.  Return type
werkzeug.wrappers.request.Request


static json_dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)
The serialization function used when json is passed.


request_class
alias of werkzeug.wrappers.request.Request


server_protocol = 'HTTP/1.1'
the server protocol to use. defaults to HTTP/1.1


wsgi_version = (1, 0)
the wsgi version to use. defaults to (1, 0)


class werkzeug.datastructures.EnvironHeaders(environ)
Read only version of the headers from a WSGI environment. This provides the same interface as Headers and is constructed from a WSGI environment. 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.


class werkzeug.utils.environ_property(name, default=None, load_func=None, dump_func=None, read_only=None, doc=None)
Maps request attributes to environment variables. This works not only for the Werkzeug request object, but also any other class with an environ attribute: >>> class Test(object):
...     environ = {'key': 'value'}
...     test = environ_property('key')
>>> var = Test()
>>> var.test
'value'
 If you pass it a second value it’s used as default if the key does not exist, the third one can be a converter that takes a value and converts it. If it raises ValueError or TypeError the default value is used. If no default value is provided None is used. Per default the property is read only. You have to explicitly enable it by passing read_only=False to the constructor.


werkzeug.utils.escape(s)
Replace &, <, >, ", and ' with HTML-safe sequences. None is escaped to an empty string.  Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use MarkupSafe instead.   Parameters
s (Any) –   Return type
str


class werkzeug.datastructures.ETags(strong_etags=None, weak_etags=None, star_tag=False)
A set that can be used to check if one etag is present in a collection of etags.
as_set(include_weak=False)
Convert the ETags object into a python set. Per default all the weak etags are not part of this set.

contains(etag)
Check if an etag is part of the set ignoring weak tags. It is also possible to use the in operator.

contains_raw(etag)
When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only.

contains_weak(etag)
Check if an etag is part of the set including weak and strong tags.

is_strong(etag)
Check if an etag is strong.

is_weak(etag)
Check if an etag is weak.

to_header()
Convert the etags set into a HTTP header string.


as_set(include_weak=False)
Convert the ETags object into a python set. Per default all the weak etags are not part of this set.


contains(etag)
Check if an etag is part of the set ignoring weak tags. It is also possible to use the in operator.


contains_raw(etag)
When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only.


contains_weak(etag)
Check if an etag is part of the set including weak and strong tags.


is_strong(etag)
Check if an etag is strong.


to_header()
Convert the etags set into a HTTP header string.


werkzeug.wsgi.extract_path_info(environ_or_baseurl, path_or_url, charset='utf-8', errors='werkzeug.url_quote', collapse_http_schemes=True)
Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a string. The URLs might also be IRIs. If the path info could not be determined, None is returned. Some examples: >>> extract_path_info('http://example.com/app', '/app/hello')
'/hello'
>>> extract_path_info('http://example.com/app',
...                   'https://example.com/app/hello')
'/hello'
>>> extract_path_info('http://example.com/app',
...                   'https://example.com/app/hello',
...                   collapse_http_schemes=False) is None
True
 Instead of providing a base URL you can also pass a WSGI environment.  Parameters

environ_or_baseurl (Union[str, WSGIEnvironment]) – a WSGI environment dict, a base URL or base IRI. This is the root of the application.
path_or_url (Union[str, werkzeug.urls._URLTuple]) – an absolute path from the server root, a relative path (in which case it’s the path info) or a full URL.
charset (str) – the charset for byte data in URLs
errors (str) – the error handling on decode
collapse_http_schemes (bool) – if set to False the algorithm does not assume that http and https on the same server point to the same resource.   Return type
Optional[str]    Changelog Changed in version 0.15: The errors parameter defaults to leaving invalid bytes quoted instead of replacing them.   New in version 0.6.


FastCGI A very popular deployment setup on servers like lighttpd and nginx is FastCGI. To use your WSGI application with any of them you will need a FastCGI server first. The most popular one is flup which we will use for this guide. Make sure to have it installed.  Creating a .fcgi file First you need to create the FastCGI server file. Let’s call it yourapplication.fcgi: #!/usr/bin/python
from flup.server.fcgi import WSGIServer
from yourapplication import make_app

if __name__ == '__main__':
    application = make_app()
    WSGIServer(application).run()
 This is enough for Apache to work, however ngingx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. For that to work you need to pass the path to the socket to the WSGIServer: WSGIServer(application, bindAddress='/path/to/fcgi.sock').run()
 The path has to be the exact same path you define in the server config. Save the yourapplication.fcgi file somewhere you will find it again. It makes sense to have that in /var/www/yourapplication or something similar. Make sure to set the executable bit on that file so that the servers can execute it: # chmod +x /var/www/yourapplication/yourapplication.fcgi
   Configuring lighttpd A basic FastCGI configuration for lighttpd looks like this: fastcgi.server = ("/yourapplication.fcgi" =>
    ((
        "socket" => "/tmp/yourapplication-fcgi.sock",
        "bin-path" => "/var/www/yourapplication/yourapplication.fcgi",
        "check-local" => "disable",
        "max-procs" -> 1
    ))
)

alias.url = (
    "/static/" => "/path/to/your/static"
)

url.rewrite-once = (
    "^(/static.*)$" => "$1",
    "^(/.*)$" => "/yourapplication.fcgi$1"
 Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to /yourapplication. See the Lighty docs for more information on FastCGI and Python.   Configuring nginx Installing FastCGI applications on nginx is a bit tricky because by default some FastCGI parameters are not properly forwarded. A basic FastCGI configuration for nginx looks like this: location /yourapplication/ {
    include fastcgi_params;
    if ($uri ~ ^/yourapplication/(.*)?) {
        set $path_url $1;
    }
    fastcgi_param PATH_INFO $path_url;
    fastcgi_param SCRIPT_NAME /yourapplication;
    fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;
}
 This configuration binds the application to /yourapplication. If you want to have it in the URL root it’s a bit easier because you don’t have to figure out how to calculate PATH_INFO and SCRIPT_NAME: location /yourapplication/ {
    include fastcgi_params;
    fastcgi_param PATH_INFO $fastcgi_script_name;
    fastcgi_param SCRIPT_NAME "";
    fastcgi_pass unix:/tmp/yourapplication-fcgi.sock;
}
 Since Nginx doesn’t load FastCGI apps, you have to do it by yourself. You can either write an init.d script for that or execute it inside a screen session: $ screen
$ /var/www/yourapplication/yourapplication.fcgi
   Debugging FastCGI deployments tend to be hard to debug on most webservers. Very often the only thing the server log tells you is something along the lines of “premature end of headers”. In order to debug the application the only thing that can really give you ideas why it breaks is switching to the correct user and executing the application by hand. This example assumes your application is called application.fcgi and that your webserver user is www-data: $ su www-data
$ cd /var/www/yourapplication
$ python application.fcgi
Traceback (most recent call last):
  File "yourapplication.fcg", line 4, in <module>
ImportError: No module named yourapplication
 In this case the error seems to be “yourapplication” not being on the python path. Common problems are:  relative paths being used. Don’t rely on the current working directory the code depending on environment variables that are not set by the web server. different python interpreters being used.


class werkzeug.datastructures.FileMultiDict(mapping=None)
A special MultiDict that has convenience methods to add files to it. This is used for EnvironBuilder and generally useful for unittesting.  Changelog New in version 0.5.
add_file(name, file, filename=None, content_type=None)
Adds a new file to the dict. file can be a file name or a file-like or a FileStorage object.  Parameters

name – the name of the field.
file – a filename or file-like object
filename – an optional filename
content_type – an optional content type


add_file(name, file, filename=None, content_type=None)
Adds a new file to the dict. file can be a file name or a file-like or a FileStorage object.  Parameters

name – the name of the field.
file – a filename or file-like object
filename – an optional filename
content_type – an optional content type


class werkzeug.datastructures.FileStorage(stream=None, filename=None, name=None, content_type=None, content_length=None, headers=None)
The FileStorage class is a thin wrapper over incoming files. It is used by the request object to represent uploaded files. All the attributes of the wrapper stream are proxied by the file storage so it’s possible to do storage.read() instead of the long form storage.stream.read().
stream
The input stream for the uploaded file. This usually points to an open temporary file.

filename
The filename of the file on the client.

name
The name of the form field.

headers
The multipart headers as Headers object. This usually contains irrelevant information but in combination with custom multipart requests the raw headers might be interesting.  Changelog New in version 0.6.

close()
Close the underlying file if possible.

property content_length
The content-length sent in the header. Usually not available

property content_type
The content-type sent in the header. Usually not available

property mimetype
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'.  Changelog New in version 0.7.

property mimetype_params
The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.  Changelog New in version 0.7.

save(dst, buffer_size=16384)
Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB. For secure file saving also have a look at secure_filename().  Parameters

dst – a filename, os.PathLike, or open file object to write to.
buffer_size – Passed as the length parameter of shutil.copyfileobj().     Changelog Changed in version 1.0: Supports pathlib.


close()
Close the underlying file if possible.


filename
The filename of the file on the client.


headers
The multipart headers as Headers object. This usually contains irrelevant information but in combination with custom multipart requests the raw headers might be interesting.  Changelog New in version 0.6.


save(dst, buffer_size=16384)
Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB. For secure file saving also have a look at secure_filename().  Parameters

dst – a filename, os.PathLike, or open file object to write to.
buffer_size – Passed as the length parameter of shutil.copyfileobj().     Changelog Changed in version 1.0: Supports pathlib.


stream
The input stream for the uploaded file. This usually points to an open temporary file.


class werkzeug.wsgi.FileWrapper(file, buffer_size=8192)
This class can be used to convert a file-like object into an iterable. It yields buffer_size blocks until the file is fully read. You should not use this class directly but rather use the wrap_file() function that uses the WSGI server’s file wrapper support if it’s available.  Changelog New in version 0.5.  If you’re using this object together with a Response you have to use the direct_passthrough mode.  Parameters

file (BinaryIO) – a file-like object with a read() method.
buffer_size (int) – number of bytes for one iteration.   Return type
None


werkzeug.utils.find_modules(import_path, include_packages=False, recursive=False)
Finds all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application. Packages are not returned unless include_packages is True. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module.  Parameters

import_path (str) – the dotted name for the package to find child modules.
include_packages (bool) – set to True if packages should be returned, too.
recursive (bool) – set to True if recursion should happen.   Returns
generator  Return type
Iterator[str]


class werkzeug.routing.FloatConverter(map, min=None, max=None, signed=False)
This converter only accepts floating point values: Rule("/probability/<float:probability>")
 By default it only accepts unsigned, positive values. The signed parameter will enable signed, negative values. Rule("/offset/<float(signed=True):offset>")
  Parameters

map (Map) – The Map.
min (Optional[float]) – The minimal value.
max (Optional[float]) – The maximal value.
signed (bool) – Allow signed (negative) values.   Return type
None    Changelog New in version 0.15: The signed parameter.


class werkzeug.formparser.FormDataParser(stream_factory=None, charset='utf-8', errors='replace', max_form_memory_size=None, max_content_length=None, cls=None, silent=True)
This class implements parsing of form data for Werkzeug. By itself it can parse multipart and url encoded form data. It can be subclassed and extended but for most mimetypes it is a better idea to use the untouched stream and expose it as separate attributes on a request object.  Changelog New in version 0.8.   Parameters

stream_factory (Optional[TStreamFactory]) – An optional callable that returns a new read and writeable file descriptor. This callable works the same as Response._get_file_stream().
charset (str) – The character set for URL and url encoded form data.
errors (str) – The encoding error behavior.
max_form_memory_size (Optional[int]) – the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an RequestEntityTooLarge exception is raised.
max_content_length (Optional[int]) – If this is provided and the transmitted data is longer than this value an RequestEntityTooLarge exception is raised.
cls (Optional[Type[werkzeug.datastructures.MultiDict]]) – an optional dict class to use. If this is not specified or None the default MultiDict is used.
silent (bool) – If set to False parsing errors will not be caught.   Return type
None


werkzeug.http.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 (bytes) –   Return type
str


werkzeug.security.generate_password_hash(password, method='pbkdf2:sha256', salt_length=16)
Hash a password with the given method and salt with a string of the given length. The format of the string returned includes the method that was used so that check_password_hash() can check the hash. The format for the hashed string looks like this: method$salt$hash
 This method can not generate unsalted passwords but it is possible to set param method=’plain’ in order to enforce plaintext passwords. If a salt is used, hmac is used internally to salt the password. If PBKDF2 is wanted it can be enabled by setting the method to pbkdf2:method:iterations where iterations is optional: pbkdf2:sha256:80000$salt$hash
pbkdf2:sha256$salt$hash
  Parameters

password (str) – the password to hash.
method (str) – the hash method to use (one that hashlib supports). Can optionally be in the format pbkdf2:method:iterations to enable PBKDF2.
salt_length (int) – the length of the salt in letters.   Return type
str


werkzeug.wsgi.get_content_length(environ)
Returns the content length from the WSGI environment as integer. If it’s not available or chunked transfer encoding is used, None is returned.  Changelog New in version 0.9.   Parameters
environ (WSGIEnvironment) – the WSGI environ to fetch the content length from.  Return type
Optional[int]


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


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.


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.


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.


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.


get_all(name)
Return a list of all the values for the named field. This method is compatible with the wsgiref get_all() method.


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.


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.


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.


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.


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


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.


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')])
'
foo bar
'
 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>"))
'
<foo>
'
  Deprecated since version 2.0: Will be removed in Werkzeug 2.1.


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


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


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.


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.


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


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


class werkzeug.datastructures.ImmutableList(iterable=(), /)
An immutable list.  Changelog New in version 0.5.   Private


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


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


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


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


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.


original_exception
The original exception that caused this 500 error. Can be used by frameworks to provide context when handling unexpected errors.


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


class werkzeug.datastructures.LanguageAccept(values=())
Like Accept but with normalization for language tags.


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


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


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


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)


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


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


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


_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


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.


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]


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


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


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