Utilities
Various utility functions shipped with Werkzeug.
HTML Helpers
Per default there are two instances of that class. The html one, andthe xhtml one for those two dialects. The class uses keyword parametersand positional parameters to generate small snippets of HTML.
Keyword parameters are converted to XML/SGML attributes, positionalarguments are used as children. Because Python accepts positionalarguments before keyword arguments it’s a good idea to use a list with thestar-syntax for some children:
- >>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ',
- ... html.a('bar', href='bar.html')])
- u'<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'
This class works around some browser limitations and can not be used forarbitrary SGML/XML generation. For that purpose lxml and similarlibraries exist.
Calling the builder escapes the string passed:
- >>> html.p(html("<foo>"))
- u'<p><foo></p>'
werkzeug.utils.
escape
(s, quote=None)- Replace special characters “&”, “<”, “>” and (“) to HTML-safe sequences.
There is a special handling for None which escapes to an empty string.
Changed in version 0.9: quote is now implicitly on.
Parameters:
- s – the string to escape.
- quote – ignored.
werkzeug.utils.
unescape
(s)- The reverse function of escape. This unescapes all the HTMLentities, not only the XML entities inserted by escape.
Parameters:s – the string to unescape.
General Helpers
- class
werkzeug.utils.
cachedproperty
(_func, name=None, doc=None) - A decorator that converts a function into a lazy property. Thefunction wrapped is called the first time to retrieve the resultand then that calculated result is used the next time you accessthe value:
- class Foo(object):
- @cached_property
- def foo(self):
- # calculate something important here
- return 42
The class has to have a dict in order for this property towork.
- class
werkzeug.utils.
environproperty
(_name, default=None, load_func=None, dump_func=None, read_only=None, doc=None) - Maps request attributes to environment variables. This works not onlyfor the Werzeug request object, but also any other class with anenviron 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 notexist, the third one can be a converter that takes a value and convertsit. If it raises ValueError
or TypeError
the default valueis used. If no default value is provided None is used.
Per default the property is read only. You have to explicitly enable itby passing read_only=False
to the constructor.
- class
werkzeug.utils.
headerproperty
(_name, default=None, load_func=None, dump_func=None, read_only=None, doc=None) - Like environ_property but for headers.
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 are301, 302, 303, 305, 307, and 308. 300 is not supported becauseit’s not a real redirect and 304 because it’s the answer for arequest 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 usingthe iri_to_uri()
function.
New in version 0.10: The class used for the Response object can now be passed in.
Parameters:
- 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 aresponse. The default is
werkzeug.wrappers.Response
ifunspecified.
werkzeug.utils.
appendslash_redirect
(_environ, code=301)- Redirects to the same URL but with a slash appended. The behaviorof this function is undefined if the path ends with a slash already.
Parameters:
- environ – the WSGI environment for the request that triggersthe redirect.
- code – the status code for the redirect.
werkzeug.utils.
importstring
(_import_name, silent=False)- Imports an object based on a string. This is useful if you want touse import paths as endpoints or something similar. An import path canbe 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 – the dotted name for the object to import.
- silent – if set to True import errors are ignored andNone is returned instead.Returns:imported object
werkzeug.utils.
findmodules
(_import_path, include_packages=False, recursive=False)- Finds all the modules below a package. This can be useful toautomatically import all views / controllers so that their metaclasses /function decorators have a chance to register themselves on theapplication.
Packages are not returned unless include_packages is True. This canalso recursively list modules but in that case it will import all thepackages to get the correct load path of that module.
Parameters:
- import_path – the dotted name for the package to find child modules.
- include_packages – set to True if packages should be returned, too.
- recursive – set to True if recursion should happen.Returns:generator
werkzeug.utils.
validatearguments
(_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 tothe function without causing a TypeError because the function signatureis incompatible. If drop_extra is set to True (which is the default)any extra positional or keyword arguments are dropped automatically.
The exception raised provides three attributes:
- missing
- A set of argument names that the function expected but wheremissing.
- extra
- A dict of keyword arguments that the function can not handle butwhere provided.
- extra_positional
- A list of values that where given by positional argument but thefunction cannot accept.This can be useful for decorators that forward user submitted data toa 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
Parameters:
- func – the function the validation is performed against.
- args – a tuple of positional arguments.
- kwargs – a dict of keyword arguments.
- drop_extra – set to False if you don’t want extra argumentsto be silently dropped.Returns:tuple in the form
(args, kwargs)
.
werkzeug.utils.
securefilename
(_filename)- Pass it a filename and it will return a secure version of it. Thisfilename can then safely be stored on a regular file system and passedto
os.path.join()
. The filename returned is an ASCII only stringfor maximum portability.
On windows systems the function also makes sure that the file is notnamed after one of the special device files.
- >>> secure_filename("My cool movie.mov")
- 'My_cool_movie.mov'
- >>> secure_filename("../../../etc/passwd")
- 'etc_passwd'
- >>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
- 'i_contain_cool_umlauts.txt'
The function might return an empty filename. It’s your responsibilityto ensure that the filename is unique and that you abort orgenerate a random filename if the function returned an empty one.
New in version 0.5.
Parameters:filename – the filename to secure
werkzeug.utils.
bindarguments
(_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 usefulto implement a cache decorator that uses the function arguments to buildthe 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.
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 agentstring and you can inspect some of the details from the user agentstring via the attributes. The following attributes exist:
string
the raw user agent string
the browser platform. The following platforms are currentlyrecognized:
- aix
- amiga
- android
- blackberry
- bsd
- chromeos
- dragonflybsd
- freebsd
- hpux
- ipad
- iphone
- irix
- linux
- macos
- netbsd
- openbsd
- sco
- solaris
- symbian
- wii
- windows
browser
the name of the browser. The following browsers are currentlyrecognized:
- aol *
- ask *
- baidu *
- bing *
- camino
- chrome
- edge
- firefox
- galeon
- google *
- kmeleon
- konqueror
- links
- lynx
- mozilla
- msie
- msn
- netscape
- opera
- safari
- seamonkey
- webkit
- yahoo (Browsers marked with a star (
) are crawlers.)
the version of the browser
- the language of the browser
Security Helpers
New in version 0.6.1.
werkzeug.security.
generatepassword_hash
(_password, method='pbkdf2:sha256', salt_length=8)- Hash a password with the given method and salt with a string ofthe given length. The format of the string returned includes the methodthat 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 possibleto 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 topbkdf2:method:iterations
where iterations is optional:
- pbkdf2:sha256:80000$salt$hash
- pbkdf2:sha256$salt$hash
Parameters:
- password – the password to hash.
- method – the hash method to use (one that hashlib supports). Canoptionally be in the format
pbkdf2:<method>[:iterations]
to enable PBKDF2. - salt_length – the length of the salt in letters.
werkzeug.security.
checkpassword_hash
(_pwhash, password)- check a password against a given salted and hashed password value.In order to support unsalted legacy passwords this method supportsplain text passwords, md5 and sha1 hashes (both salted and unsalted).
Returns True if the password matched, False otherwise.
Parameters:
- pwhash – a hashed string like returned by
generate_password_hash()
. - password – the plaintext password to compare against the hash.
werkzeug.security.
safestr_cmp
(_a, b)- This function compares strings in somewhat constant time. Thisrequires that the length of at least one string is known in advance.
Returns True if the two strings are equal, or False if they are not.
New in version 0.7.
werkzeug.security.
safejoin
(_directory, *pathnames)- Safely join zero or more untrusted path components to a basedirectory to avoid escaping the base directory.
Parameters:
- directory – The trusted base directory.
- pathnames – The untrusted path components relative to thebase directory.Returns:A safe path, otherwise
None
.
werkzeug.security.
pbkdf2hex
(_data, salt, iterations=150000, keylen=None, hashfunc=None)- Like
pbkdf2_bin()
, but returns a hex-encoded string.
New in version 0.9.
Parameters:
- 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 thestring name of a known hash function, or a functionfrom the hashlib module. Defaults to sha256.
werkzeug.security.
pbkdf2bin
(_data, salt, iterations=150000, keylen=None, hashfunc=None)- Returns a binary digest for the PBKDF2 hash algorithm of data_with the given _salt. It iterates iterations times and produces akey of keylen bytes. By default, SHA-256 is used as hash function;a different hashlib hashfunc can be provided.
New in version 0.9.
Parameters:
- 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 providedthe digest size will be used.
- hashfunc – the hash function to use. This can either be thestring name of a known hash function or a functionfrom the hashlib module. Defaults to sha256.