Utilities
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
htmlone, and thexhtmlone for those two dialects. The class uses keyword parameters and positional parameters to generate small snippets of HTML.Keyword parameters are converted to XML/SGML attributes, positional arguments are used as children. Because Python accepts positional arguments before keyword arguments it’s a good idea to use a list with the star-syntax for some children:
>>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ', ... html.a('bar', href='bar.html')]) '<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'This class works around some browser limitations and can not be used for arbitrary SGML/XML generation. For that purpose lxml and similar libraries exist.
Calling the builder escapes the string passed:
>>> html.p(html("<foo>")) '<p><foo></p>'Deprecated since version 2.0: Will be removed in Werkzeug 2.1.
-
werkzeug.utils.escape(s) -
Replace
&,<,>,", and'with HTML-safe sequences.Noneis 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
General Helpers
-
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 cacheThe class must have a
__dict__for this to work.Changed in version 2.0:
del obj.nameclears the cached value.
-
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... 42You 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.nameinstead.
-
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
ValueErrororTypeErrorthe default value is used. If no default value is providedNoneis used.Per default the property is read only. You have to explicitly enable it by passing
read_only=Falseto the constructor.
-
class werkzeug.utils.header_property(name, default=None, load_func=None, dump_func=None, read_only=None, doc=None) -
Like
environ_propertybut 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 are 301, 302, 303, 305, 307, and 308. 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.
Changelog
New in version 0.10: The class used for the Response object can now be passed in.
New in version 0.6: The location can now be a unicode string that is encoded using the
iri_to_uri()function.- Parameters
-
- location (str) – the location the response should redirect to.
- code (int) – the redirect status code. defaults to 302.
-
Response (class) – a Response class to use when instantiating a response. The default is
werkzeug.wrappers.Responseif unspecified.
- Return type
-
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.
-
werkzeug.utils.send_file(path_or_file, environ, mimetype=None, as_attachment=False, download_name=None, conditional=True, etag=True, last_modified=None, max_age=None, use_x_sendfile=False, response_class=None, _root_path=None) -
Send the contents of a file to the client.
The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with
io.BytesIO.Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn’t intend.
If the WSGI server sets a
file_wrapperinenviron, it is used, otherwise Werkzeug’s built-in wrapper is used. Alternatively, if the HTTP server supportsX-Sendfile,use_x_sendfile=Truewill tell the server to send the given path, which is much more efficient than reading it in Python.- Parameters
-
- path_or_file (Union[os.PathLike, str, BinaryIO]) – The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data.
- environ (WSGIEnvironment) – The WSGI environ for the current request.
- mimetype (Optional[str]) – The MIME type to send for the file. If not provided, it will try to detect it from the file name.
- as_attachment (bool) – Indicate to a browser that it should offer to save the file instead of displaying it.
- download_name (Optional[str]) – The default name browsers will use when saving the file. Defaults to the passed file name.
-
conditional (bool) – Enable conditional and range responses based on request headers. Requires passing a file path and
environ. - etag (Union[bool, str]) – Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead.
- last_modified (Optional[Union[datetime.datetime, int, float]]) – The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path.
-
max_age (Optional[Union[int, Callable[[Optional[Union[os.PathLike, str]]], int]]]) – How long the client should cache the file, in seconds. If set,
Cache-Controlwill bepublic, otherwise it will beno-cacheto prefer conditional caching. -
use_x_sendfile (bool) – Set the
X-Sendfileheader to let the server to efficiently send the file. Requires support from the HTTP server. Requires passing a file path. -
response_class (Optional[Type[Response]]) – Build the response using this class. Defaults to
Response. -
_root_path (Optional[Union[os.PathLike, str]]) – Do not use. For internal use only. Use
send_from_directory()to safely send files under a path.
- Return type
New in version 2.0: Adapted from Flask’s implementation.
Changed in version 2.0:
download_namereplaces Flask’sattachment_filenameparameter. Ifas_attachment=False, it is passed withContent-Disposition: inlineinstead.Changed in version 2.0:
max_agereplaces Flask’scache_timeoutparameter.conditionalis enabled andmax_ageis not set by default.Changed in version 2.0:
etagreplaces Flask’sadd_etagsparameter. It can be a string to use instead of generating one.Changed in version 2.0: If an encoding is returned when guessing
mimetypefromdownload_name, set theContent-Encodingheader.
-
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
silentis True the return value will beNoneif the import fails.
-
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_packagesisTrue. 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.
-
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 aTypeErrorbecause the function signature is incompatible. Ifdrop_extrais set toTrue(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 where missing.
-
extra -
A dict of keyword arguments that the function can not handle but where provided.
-
extra_positional -
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- 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
Falseif you don’t want extra arguments to be silently dropped.
- Returns
-
tuple in the form
(args, kwargs).
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use
inspect.signature()instead. -
-
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.
>>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename('i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt'The function might return an empty filename. It’s your responsibility to ensure that the filename is unique and that you abort or generate a random filename if the function returned an empty one.
Changelog
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
bind_argumentsreturns 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
dictof bound keyword arguments.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use
Signature.bind()instead.
URL Helpers
Please refer to URL Helpers.
User Agent API
-
class werkzeug.user_agent.UserAgent(string) -
Represents a parsed user agent header value.
The default implementation does no parsing, only the
stringattribute is set. A subclass may parse the string to set the common attributes or expose other information. Setwerkzeug.wrappers.Request.user_agent_classto use a subclass.New in version 2.0: This replaces the previous
useragentsmodule, but does not provide a built-in parser.-
platform: Optional[str] = None -
The OS name, if it could be parsed from the string.
-
browser: Optional[str] = None -
The browser name, if it could be parsed from the string.
-
version: Optional[str] = None -
The browser version, if it could be parsed from the string.
-
language: Optional[str] = None -
The browser language, if it could be parsed from the string.
-
string: str -
The original header value.
-
to_header() -
Convert to a header value.
- Return type
-
UserAgent Parsing (deprecated)
Deprecated since version 2.0: This module will be removed in Werkzeug 2.1. Subclass werkzeug.user_agent.UserAgent to use a dedicated parser instead.
-
class werkzeug.useragents.UserAgent(environ_or_string) -
Represents a parsed user agent header value.
This uses a basic parser to try to extract some information from the header.
- Parameters
-
environ_or_string (t.Union[str, WSGIEnvironment]) – The header value to parse, or a WSGI environ containing the header.
- Return type
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Subclass
werkzeug.user_agent.UserAgent(note the new module name) to use a dedicated parser instead.Changed in version 2.0: Passing a WSGI environ is deprecated and will be removed in 2.1.
-
to_header() -
Convert to a header value.
- Return type
Security Helpers
Changelog
New in version 0.6.1.
-
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:iterationswhere iterations is optional:pbkdf2:sha256:80000$salt$hash pbkdf2:sha256$salt$hash
-
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
Trueif the password matched,Falseotherwise.- Parameters
-
-
pwhash (str) – a hashed string like returned by
generate_password_hash(). - password (str) – the plaintext password to compare against the hash.
-
pwhash (str) – a hashed string like returned by
- Return type
-
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
Trueif the two strings are equal, orFalseif they are not.Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use
hmac.compare_digest()instead.Changelog
New in version 0.7.
-
werkzeug.security.safe_join(directory, *pathnames) -
Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory.
-
werkzeug.security.pbkdf2_hex(data, salt, iterations=260000, keylen=None, hashfunc=None) -
Like
pbkdf2_bin(), but returns a hex-encoded string.- Parameters
-
- data (Union[str, bytes]) – the data to derive.
- salt (Union[str, bytes]) – the salt for the derivation.
- iterations (int) – the number of iterations.
- keylen (Optional[int]) – the length of the resulting key. If not provided, the digest size will be used.
- hashfunc (Optional[Union[str, Callable]]) – 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.
- Return type
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use
hashlib.pbkdf2_hmac()instead.Changelog
New in version 0.9.
-
werkzeug.security.pbkdf2_bin(data, salt, iterations=260000, keylen=None, hashfunc=None) -
Returns a binary digest for the PBKDF2 hash algorithm of
datawith the givensalt. It iteratesiterationstimes and produces a key ofkeylenbytes. By default, SHA-256 is used as hash function; a different hashlibhashfunccan be provided.- Parameters
-
- data (Union[str, bytes]) – the data to derive.
- salt (Union[str, bytes]) – the salt for the derivation.
- iterations (int) – the number of iterations.
- keylen (Optional[int]) – the length of the resulting key. If not provided the digest size will be used.
- hashfunc (Optional[Union[str, Callable]]) – 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.
- Return type
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use
hashlib.pbkdf2_hmac()instead.Changelog
New in version 0.9.
Logging
Werkzeug uses standard Python logging. The logger is named "werkzeug".
import logging
logger = logging.getLogger("werkzeug")
If the logger level is not set, it will be set to INFO on first use. If there is no handler for that level, a StreamHandler is added.
© 2007–2021 Pallets
Licensed under the BSD 3-clause License.
https://werkzeug.palletsprojects.com/en/2.0.x/utils/