Various utility functions shipped with Werkzeug.
HTML Helpers
class werkzeug.utils.HTMLBuilder(dialect)
Helper object for HTML generation.
Per default there are two instances of that class. The [UNKNOWN NODE title_reference] one, and the [UNKNOWN NODE title_reference] 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:
[UNKNOWN NODE doctest_block]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:
[UNKNOWN NODE doctest_block]werkzeug.utils.escape(s, quote=None)
Replace special characters “&”, “<”, “>” and (“) to HTML-safe sequences.
There is a special handling for [UNKNOWN NODE title_reference] which escapes to an empty string.
Changed in version 0.9: [UNKNOWN NODE title_reference] is now implicitly on.
- s – the string to escape.
- quote – ignored.
werkzeug.utils.unescape(s)
The reverse function of [UNKNOWN NODE title_reference]. This unescapes all the HTML entities, not only the XML entities inserted by [UNKNOWN NODE title_reference].
General Helpers
class werkzeug.utils.cached_property(func, name=None, doc=None)
A decorator that converts a function into a lazy property. The function wrapped is called the first time to retrieve the result and then that calculated result is used the next time you access the value:
class Foo(object):
@cached_property
def foo(self):
# calculate something important here
return 42
The class has to have a [UNKNOWN NODE title_reference] in order for this property to work.
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 Werzeug request object, but also any other class with an environ attribute:
[UNKNOWN NODE doctest_block]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 [UNKNOWN NODE title_reference] is used.
Per default the property is read only. You have to explicitly enable it
by passing read_only=False
to the constructor.
class werkzeug.utils.header_property(name, default=None, load_func=None, dump_func=None, read_only=None, doc=None)
Like [UNKNOWN NODE title_reference] but for headers.
werkzeug.utils.parse_cookie(header, charset='utf-8', errors='replace', cls=None)
Parse a cookie. Either from a string or WSGI environ.
Per default encoding errors are ignored. If you want a different behavior
you can set [UNKNOWN NODE title_reference] to 'replace'
or 'strict'
. In strict mode a
HTTPUnicodeError
is raised.
Changed in version 0.5: This function now returns a TypeConversionDict
instead of a
regular dict. The [UNKNOWN NODE title_reference] parameter was added.
- header – the header to be used to parse the cookie. Alternatively this can be a WSGI environment.
- charset – the charset for the cookie values.
- errors – the error behavior for the charset decoding.
- cls – an optional dict class to use. If this is not specified
or [UNKNOWN NODE title_reference] the default
TypeConversionDict
is used.
werkzeug.utils.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)
Creates a new Set-Cookie header without the Set-Cookie
prefix
The parameters are the same as in the cookie Morsel object in the
Python standard library but it accepts unicode data, too.
On Python 3 the return value of this function will be a unicode string, on Python 2 it will be a native string. In both cases the return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. If a unicode string is returned 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.
- max_age – should be a number of seconds, or [UNKNOWN NODE title_reference] (default) if the cookie should last only as long as the client’s browser session. Additionally [UNKNOWN NODE title_reference] objects are accepted, too.
- expires – should be a [UNKNOWN NODE title_reference] object or unix timestamp.
- path – limits the cookie to a given path, per default it will span the whole domain.
- domain – 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 domainwww.example.com
,foo.example.com
etc. Otherwise, a cookie will only be readable by the domain that set it. - secure – The cookie will only be available via HTTPS
- httponly – disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers.
- charset – the encoding for unicode values.
- sync_expires – automatically set expires if max_age is defined but expires not.
- max_size – 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 – Limits the scope of the cookie such that it will only be attached to requests if those requests are “same-site”.
werkzeug.utils.redirect(location, code=302, Response=None)
Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers.
New in version 0.6: The location can now be a unicode string that is encoded using
the iri_to_uri()
function.
New in version 0.10: The class used for the Response object can now be passed in.
- location – the location the response should redirect to.
- code – the redirect status code. defaults to 302.
- Response (
class
) – a Response class to use when instantiating a response. The default iswerkzeug.wrappers.Response
if unspecified.
werkzeug.utils.append_slash_redirect(environ, code=301)
Redirects to the same URL but with a slash appended. The behavior of this function is undefined if the path ends with a slash already.
- environ – the WSGI environment for the request that triggers the redirect.
- code – the status code for the redirect.
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 [UNKNOWN NODE title_reference] is True the return value will be [UNKNOWN NODE title_reference] if the import fails.
- import_name – the dotted name for the object to import.
- silent – if set to [UNKNOWN NODE title_reference] import errors are ignored and [UNKNOWN NODE title_reference] is returned instead.
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 [UNKNOWN NODE title_reference] is [UNKNOWN NODE title_reference]. 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.
- import_path – the dotted name for the package to find child modules.
- include_packages – set to [UNKNOWN NODE title_reference] if packages should be returned, too.
- recursive – set to [UNKNOWN NODE title_reference] if recursion should happen.
werkzeug.utils.validate_arguments(func, args, kwargs, drop_extra=True)
Checks if the function accepts the arguments and keyword arguments.
Returns a new (args, kwargs)
tuple that can safely be passed to
the function without causing a [UNKNOWN NODE title_reference] because the function signature
is incompatible. If [UNKNOWN NODE title_reference] is set to [UNKNOWN NODE title_reference] (which is the default)
any extra positional or keyword arguments are dropped automatically.
The exception raised provides three attributes:
- [UNKNOWN NODE title_reference]
- A set of argument names that the function expected but where missing.
- [UNKNOWN NODE title_reference]
- A dict of keyword arguments that the function can not handle but where provided.
- [UNKNOWN NODE title_reference]
- A list of values that where given by positional argument but the function cannot accept.
This can be useful for decorators that forward user submitted data to a view function:
from werkzeug.utils import ArgumentValidationError, validate_arguments
def sanitize(f):
def proxy(request):
data = request.values.to_dict()
try:
args, kwargs = validate_arguments(f, (request,), data)
except ArgumentValidationError:
raise BadRequest('The browser failed to transmit all '
'the data expected.')
return f(*args, **kwargs)
return proxy
- func – the function the validation is performed against.
- args – a tuple of positional arguments.
- kwargs – a dict of keyword arguments.
- drop_extra – set to [UNKNOWN NODE title_reference] if you don’t want extra arguments to be silently dropped.
(args, kwargs)
.werkzeug.utils.secure_filename(filename)
Pass it a filename and it will return a secure version of it. This
filename can then safely be stored on a regular file system and passed
to os.path.join()
. The filename returned is an ASCII only string
for maximum portability.
On windows systems the function also makes sure that the file is not named after one of the special device files.
[UNKNOWN NODE doctest_block]The function might return an empty filename. It’s your responsibility to ensure that the filename is unique and that you generate random filename if the function returned an empty one.
New in version 0.5.
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 [UNKNOWN NODE title_reference] 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.
- func – the function the arguments should be bound for.
- args – tuple of positional arguments.
- kwargs – a dict of keyword arguments.
dict
of bound keyword arguments.URL Helpers
Please refer to URL Helpers.
UserAgent Parsing
class werkzeug.useragents.UserAgent(environ_or_string)
Represents a user agent. Pass it a WSGI environment or a user agent string and you can inspect some of the details from the user agent string via the attributes. The following attributes exist:
string
the raw user agent string
platform
the browser platform. The following platforms are currently recognized:
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
browser
the name of the browser. The following browsers are currently recognized:
- [UNKNOWN NODE title_reference] *
- [UNKNOWN NODE title_reference] *
- [UNKNOWN NODE title_reference] *
- [UNKNOWN NODE title_reference] *
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference] *
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference]
- [UNKNOWN NODE title_reference] *
(Browsers marked with a star (*
) are crawlers.)
version
the version of the browser
language
the language of the browser
Security Helpers
New in version 0.6.1.
werkzeug.security.generate_password_hash(password, method='pbkdf2:sha256', salt_length=8)
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
- password – the password to hash.
- method – the hash method to use (one that hashlib supports). Can
optionally be in the format
pbkdf2:<method>[:iterations]
to enable PBKDF2. - salt_length – the length of the salt in letters.
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 [UNKNOWN NODE title_reference] if the password matched, [UNKNOWN NODE title_reference] otherwise.
- pwhash – a hashed string like returned by
generate_password_hash()
. - password – the plaintext password to compare against the hash.
werkzeug.security.safe_str_cmp(a, b)
This function compares strings in somewhat constant time. This requires that the length of at least one string is known in advance.
Returns [UNKNOWN NODE title_reference] if the two strings are equal, or [UNKNOWN NODE title_reference] if they are not.
New in version 0.7.
werkzeug.security.safe_join(directory, *pathnames)
Safely join [UNKNOWN NODE title_reference] and one or more untrusted [UNKNOWN NODE title_reference]. If this
cannot be done, this function returns None
.
- directory – the base directory.
- pathnames – the untrusted pathnames relative to that directory.
werkzeug.security.pbkdf2_hex(data, salt, iterations=50000, keylen=None, hashfunc=None)
Like pbkdf2_bin()
, but returns a hex-encoded string.
New in version 0.9.
- data – the data to derive.
- salt – the salt for the derivation.
- iterations – the number of iterations.
- keylen – the length of the resulting key. If not provided, the digest size will be used.
- hashfunc – the hash function to use. This can either be the string name of a known hash function, or a function from the hashlib module. Defaults to sha256.
werkzeug.security.pbkdf2_bin(data, salt, iterations=50000, keylen=None, hashfunc=None)
Returns a binary digest for the PBKDF2 hash algorithm of [UNKNOWN NODE title_reference] with the given [UNKNOWN NODE title_reference]. It iterates [UNKNOWN NODE title_reference] times and produces a key of [UNKNOWN NODE title_reference] bytes. By default, SHA-256 is used as hash function; a different hashlib [UNKNOWN NODE title_reference] can be provided.
New in version 0.9.
- data – the data to derive.
- salt – the salt for the derivation.
- iterations – the number of iterations.
- keylen – the length of the resulting key. If not provided the digest size will be used.
- hashfunc – the hash function to use. This can either be the string name of a known hash function or a function from the hashlib module. Defaults to sha256.