module documentation

Undocumented

Class ​Argument​Validation​Error Raised if validate_arguments fails to validate
Class cached​_property No summary
Class environ​_property 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 header​_property Like environ_property but for headers.
Class ​HTMLBuilder Helper object for HTML generation.
Class ​Import​String​Error Provides information about a failed import_string attempt.
Function append​_slash​_redirect 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.
Function bind​_arguments No summary
Function detect​_utf​_encoding Detect which UTF encoding was used to encode the given bytes.
Function escape Replace &, <, >, ", and ' with HTML-safe sequences.
Function find​_modules No summary
Function format​_string String-template format a string:
Function get​_content​_type Returns the full content type string with charset for a mimetype.
Function import​_string No summary
Function invalidate​_cached​_property Invalidates the cache for a cached_property:
Function redirect No summary
Function secure​_filename No summary
Function send​_file Send the contents of a file to the client.
Function send​_from​_directory Send a file from within a directory using send_file.
Function unescape The reverse of escape. This unescapes all the HTML entities, not only those inserted by escape.
Function validate​_arguments No summary
Variable html Undocumented
Variable xhtml Undocumented
Constant ​_T Undocumented
Variable ​_charset​_mimetypes Undocumented
Variable ​_entity​_re Undocumented
Variable ​_filename​_ascii​_strip​_re Undocumented
Variable ​_windows​_device​_files Undocumented
def 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.
Parameters
environ:WSGIEnvironmentthe WSGI environment for the request that triggers the redirect.
code:intthe status code for the redirect.
Returns
ResponseUndocumented
def 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.

Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use Signature.bind instead.
Parameters
functhe function the arguments should be bound for.
argstuple of positional arguments.
kwargsa dict of keyword arguments.
Returns
a dict of bound keyword arguments.
def detect_utf_encoding(data):

Detect which UTF encoding was used to encode the given bytes.

The latest JSON standard (RFC 8259) suggests that only UTF-8 is accepted. Older documents allowed 8, 16, or 32. 16 and 32 can be big or little endian. Some editors or libraries may prepend a BOM.

Deprecated since version 2.0: Will be removed in Werkzeug 2.1. This is built in to json.loads.
New in version 0.15.
Parameters
data:bytesBytes in unknown UTF encoding.
Returns
strUTF encoding name
Unknown Field: internal
def 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:t.AnyUndocumented
Returns
strUndocumented
def 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:strthe dotted name for the package to find child modules.
include​_packages:boolset to True if packages should be returned, too.
recursive:boolset to True if recursion should happen.
Returns
t.Iterator[str]generator
def format_string(string, context):

String-template format a string:

>>> format_string('$foo and ${foo}s', dict(foo=42))
'42 and 42s'

This does not do any attribute lookup.

Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use string.Template instead.
Parameters
string:strthe format string.
context:t.Mapping[str, t.Any]a dict with the variables to insert.
Returns
strUndocumented
def get_content_type(mimetype, charset):

Returns the full content type string with charset for a mimetype.

If the mimetype represents text, the charset parameter will be appended, otherwise the mimetype is returned unchanged.

Changed in version 0.15: Any type that ends with +xml gets a charset, not just those that start with application/. Known text types such as application/javascript are also given charsets.
Parameters
mimetype:strThe mimetype to be used as content type.
charset:strThe charset to be appended for text mimetypes.
Returns
strThe content type.
def 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:strthe dotted name for the object to import.
silent:boolif set to True import errors are ignored and None is returned instead.
Returns
t.Anyimported object
def 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:objectUndocumented
name:strUndocumented
def 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.

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.
Parameters
location:strthe location the response should redirect to.
code:intthe redirect status code. defaults to 302.
​Response:t.Optional[t.Type[Response]]Undocumented
class ​Responsea Response class to use when instantiating a response. The default is werkzeug.wrappers.Response if unspecified.
Returns
ResponseUndocumented
def 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.

New in version 0.5.
Parameters
filename:strthe filename to secure
Returns
strUndocumented
def 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_wrapper in environ, it is used, otherwise Werkzeug's built-in wrapper is used. Alternatively, if the HTTP server supports X-Sendfile, use_x_sendfile=True will tell the server to send the given path, which is much more efficient than reading it in Python.

Changed in version 2.0.2: send_file only sets a detected Content-Encoding if as_attachment is disabled.
New in version 2.0: Adapted from Flask's implementation.
Changed in version 2.0: download_name replaces Flask's attachment_filename parameter. If as_attachment=False, it is passed with Content-Disposition: inline instead.
Changed in version 2.0: max_age replaces Flask's cache_timeout parameter. conditional is enabled and max_age is not set by default.
Changed in version 2.0: etag replaces Flask's add_etags parameter. It can be a string to use instead of generating one.
Changed in version 2.0: If an encoding is returned when guessing mimetype from download_name, set the Content-Encoding header.
Parameters
path​_or​_file:t.Union[os.PathLike, str, t.IO[bytes]]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:WSGIEnvironmentThe WSGI environ for the current request.
mimetype:t.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:boolIndicate to a browser that it should offer to save the file instead of displaying it.
download​_name:t.Optional[str]The default name browsers will use when saving the file. Defaults to the passed file name.
conditional:boolEnable conditional and range responses based on request headers. Requires passing a file path and environ.
etag:t.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:t.Optional[t.Union[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:t.Optional[t.Union[int, t.Callable[[t.Optional[str]], t.Optional[int]]]]How long the client should cache the file, in seconds. If set, Cache-Control will be public, otherwise it will be no-cache to prefer conditional caching.
use​_x​_sendfile:boolSet the X-Sendfile header to let the server to efficiently send the file. Requires support from the HTTP server. Requires passing a file path.
response​_class:t.Optional[t.Type[Response]]Build the response using this class. Defaults to ~werkzeug.wrappers.Response.
​_root​_path:t.Optional[t.Union[os.PathLike, str]]Do not use. For internal use only. Use send_from_directory to safely send files under a path.
Returns
ResponseUndocumented
def send_from_directory(directory, path, environ, **kwargs):

Send a file from within a directory using send_file.

This is a secure way to serve files from a folder, such as static files or uploads. Uses ~werkzeug.security.safe_join to ensure the path coming from the client is not maliciously crafted to point outside the specified directory.

If the final path does not point to an existing regular file, returns a 404 ~werkzeug.exceptions.NotFound error.

New in version 2.0: Adapted from Flask's implementation.
Parameters
directory:t.Union[os.PathLike, str]The directory that path must be located under.
path:t.Union[os.PathLike, str]The path to the file to send, relative to directory.
environ:WSGIEnvironmentThe WSGI environ for the current request.
**kwargs:t.AnyArguments to pass to send_file.
Returns
ResponseUndocumented
def unescape(s):

The reverse of escape. This unescapes all the HTML entities, not only those inserted by escape.

Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use MarkupSafe instead.
Parameters
s:strUndocumented
Returns
strUndocumented
def 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 TypeError because the function signature is 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 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
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use inspect.signature instead.
Parameters
functhe function the validation is performed against.
argsa tuple of positional arguments.
kwargsa dict of keyword arguments.
drop​_extraset to False if you don't want extra arguments to be silently dropped.
Returns
tuple in the form (args, kwargs).
html =

Undocumented

xhtml =

Undocumented

_T =

Undocumented

Value
t.TypeVar('_T')
_charset_mimetypes: set[str] =

Undocumented

_entity_re =

Undocumented

_filename_ascii_strip_re =

Undocumented

_windows_device_files: tuple[str, ...] =

Undocumented