Utilities — Werkzeug Documentation (3.1.x)

# Utilities

Various utility functions shipped with Werkzeug.

## 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 cache

  If the class defines `__slots__`, it must add `_cache_{name}` as a slot. Alternatively, it can add `__dict__`, but that’s usually not desirable.

  Changelog

  Changed in version 2.1: Works with `__slots__`.

  Changed in version 2.0: `del obj.name` clears the cached value.

  Parameters:

    - fget (t.Callable[[t.Any], _T])

    - name (str | None)

    - doc (str | None)

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.

  Parameters:

    - name (str)

    - default (_TAccessorValue | None)

    - load_func (t.Callable[[str], _TAccessorValue] | None)

    - dump_func (t.Callable[[_TAccessorValue], str] | None)

    - read_only (bool | None)

    - doc (str | None)

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.

  Parameters:

    - name (str)

    - default (_TAccessorValue | None)

    - load_func (t.Callable[[str], _TAccessorValue] | None)

    - dump_func (t.Callable[[_TAccessorValue], str] | None)

    - read_only (bool | None)

    - doc (str | None)

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

  Added in version 0.10: The class used for the Response object can now be passed in.

  Added 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.Response` if unspecified.

  Return type:

    Response

werkzeug.utils.append_slash_redirect(environ, code=308)

  Redirect to the current URL with a slash appended.

  If the current URL is `/user/42`, the redirect URL will be `42/`. When joined to the current URL during response processing or by the browser, this will produce `/user/42/`.

  The behavior is undefined if the path ends with a slash already. If called unconditionally on a URL, it may produce a redirect loop.

  Parameters:

    - environ (WSGIEnvironment) – Use the path and query from this WSGI environment to produce the redirect URL.

    - code (int) – the status code for the redirect.

  Return type:

    Response

  Changelog

  Changed in version 2.1: Produce a relative URL that only modifies the last segment. Relevant when the current path has multiple segments.

  Changed in version 2.1: The default status code is 308 instead of 301. This preserves the request method and body.

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. Use `send_from_directory()` to safely serve user-provided paths.

  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.

  Parameters:

    - path_or_file (os.PathLike[str] | 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 (WSGIEnvironment) – The WSGI environ for the current request.

    - mimetype (str | None) – 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 (str | None) – 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 (bool | str) – Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead.

    - last_modified (datetime | int | float | None) – 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 (None | (int | t.Callable[[str | None], int | None])) – 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 (bool) – Set 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 (type[Response] | None) – Build the response using this class. Defaults to `Response`.

    - _root_path (os.PathLike[str] | str | None) – Do not use. For internal use only. Use `send_from_directory()` to safely send files under a path.

  Return type:

    Response

  Changelog

  Changed in version 2.0.2: `send_file` only sets a detected `Content-Encoding` if `as_attachment` is disabled.

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

werkzeug.utils.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 `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 `NotFound` error.

  Parameters:

    - directory (os.PathLike[str] | str) – The directory that `path` must be located under. This must not be a value provided by the client, otherwise it becomes insecure.

    - path (os.PathLike[str] | str) – The path to the file to send, relative to `directory`. This is the part of the path provided by the client, which is checked for security.

    - environ (WSGIEnvironment) – The WSGI environ for the current request.

    - kwargs (t.Any) – Arguments to pass to `send_file()`.

  Return type:

    Response

  Changelog

  Added in version 2.0: Adapted from Flask’s implementation.

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

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]

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

  Added in version 0.5.

  Parameters:

    filename (str) – the filename to secure

  Return type:

    str

## 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 `string` attribute is set. A subclass may parse the string to set the common attributes or expose other information. Set `werkzeug.wrappers.Request.user_agent_class` to use a subclass.

  Parameters:

    string (str) – The header value to parse.

  Changelog

  Added in version 2.0: This replaces the previous `useragents` module, but does not provide a built-in parser.

  platform: str | None = None

    The OS name, if it could be parsed from the string.

  browser: str | None = None

    The browser name, if it could be parsed from the string.

  version: str | None = None

    The browser version, if it could be parsed from the string.

  language: str | None = 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:

      str

## Security Helpers

werkzeug.security.generate_password_hash(password, method='scrypt', salt_length=16)

  Securely hash a password for storage. A password can be compared to a stored hash using `check_password_hash()`.

  The following methods are supported:

  - `scrypt`, the default. The parameters are `n`, `r`, and `p`, the default is `scrypt:32768:8:1`. See `hashlib.scrypt()`.

  - `pbkdf2`, less secure. The parameters are `hash_method` and `iterations`, the default is `pbkdf2:sha256:600000`. See `hashlib.pbkdf2_hmac()`.

  Default parameters may be updated to reflect current guidelines, and methods may be deprecated and removed if they are no longer considered secure. To migrate old hashes, you may generate a new hash when checking an old hash, or you may contact users with a link to reset their password.

  Parameters:

    - password (str) – The plaintext password.

    - method (str) – The key derivation function and parameters.

    - salt_length (int) – The number of characters to generate for the salt.

  Return type:

    str

  Changed in version 3.1: The default iterations for pbkdf2 was increased to 1,000,000.

  Changelog

  Changed in version 2.3: Scrypt support was added.

  Changed in version 2.3: The default iterations for pbkdf2 was increased to 600,000.

  Changed in version 2.3: All plain hashes are deprecated and will not be supported in Werkzeug 3.0.

werkzeug.security.check_password_hash(pwhash, password)

  Securely check that the given stored password hash, previously generated using `generate_password_hash()`, matches the given password.

  Methods may be deprecated and removed if they are no longer considered secure. To migrate old hashes, you may generate a new hash when checking an old hash, or you may contact users with a link to reset their password.

  Parameters:

    - pwhash (str) – The hashed password.

    - password (str) – The plaintext password.

  Return type:

    bool

  Changelog

  Changed in version 2.3: All plain hashes are deprecated and will not be supported in Werkzeug 3.0.

werkzeug.security.safe_join(directory, *untrusted)

  Safely join zero or more untrusted path components to a trusted base directory to avoid escaping the base directory.

  The untrusted path is assumed to be from/for a URL, such as for serving files. Therefore, it should only use the forward slash `/` path separator, and will be joined using that separator. On Windows, the backslash `\` separator is not allowed.

  Parameters:

    - directory (str) – The trusted base directory.

    - untrusted (str) – The untrusted path components relative to the base directory.

  Returns:

    A safe path, otherwise `None`.

  Return type:

    str | None

  Changed in version 3.1.6: Special device names in multi-segment paths are not allowed on Windows.

  Changed in version 3.1.5: More special device names, regardless of extension or trailing spaces, are not allowed on Windows.

  Changed in version 3.1.4: Special device names are not allowed on Windows.

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