Enables debugging support for a given application:
The evalex keyword argument allows evaluating expressions in a traceback’s frame context.
None


Combine multiple applications as a single WSGI application. Requests are dispatched to an application based on the path it is mounted under.
None


Create a Set-Cookie header without the Set-Cookie prefix.
The return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. 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.
str
Changed in version 1.0.0: The string 'None' is accepted for samesite.


Dump an HTTP header again. This is the reversal of parse_list_header(), parse_set_header() and parse_dict_header(). This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs.
str


Prefixes all endpoints (which must be strings for this factory) with another string. This can be useful for sub applications:
None


This class can be used to conveniently create a WSGI environment for testing purposes. It can be used to quickly create WSGI environments or request objects from arbitrary data.
The signature of this class is also used in some other places as of Werkzeug 0.5 (create_environ(), Response.from_values(), Client.open()). Because of this most of the functionality is available through the constructor alone.
Files and regular form data can be manipulated independently of each other with the form and files attributes, but are passed with the same argument to the constructor: data.
data can be any of these values:
a dict or MultiDict: The keys have to be strings. The values have to be either any of the following objects, or a list of any of the following objects:
None
Changed in version 2.0: REQUEST_URI and RAW_URI is the full raw URI including the query string, not only the path.
Changed in version 2.0: The default request_class is Request instead of BaseRequest.
New in version 2.0: Added the auth parameter.
New in version 0.15: The json param and json_dumps() method.
New in version 0.15: The environ has keys REQUEST_URI and RAW_URI containing the path before perecent-decoding. This is not part of the WSGI PEP, but many WSGI servers include it.
Changed in version 0.6: path and base_url can now be unicode strings that are encoded with iri_to_uri().
the server protocol to use. defaults to HTTP/1.1
the wsgi version to use. defaults to (1, 0)
alias of werkzeug.wrappers.request.Request
The serialization function used when json is passed.
Turn an environ dict back into a builder. Any extra kwargs override the args extracted from the environ.
Changed in version 2.0: Path and query values are passed through the WSGI decoding dance to avoid double encoding.
New in version 0.15.
EnvironBuilder
The base URL is used to extract the URL scheme, host name, port, and root path.
The content type for the request. Reflected from and to the headers. Do not set if you set files or form for auto detection.
The mimetype (content type without charset etc.)
New in version 0.14.
The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.
New in version 0.14.
The content length as integer. Reflected from and to the headers. Do not set if you set files or form for auto detection.
A MultiDict of form values.
A FileMultiDict of uploaded files. Use add_file() to add new files.
An optional input stream. This is mutually exclusive with setting form and files, setting it will clear those. Do not provide this if the method is not POST or another method that has a body.
The query string. If you set this to a string args will no longer be available.
The URL arguments as MultiDict.
The server name (read-only, use host to set)
The server port as integer (read-only, use host to set)
Closes all files. If you put real file objects into the files dict you can call this method to automatically close them all in one go.
None
Return the built environ.
Changed in version 0.15: The content type and length headers are set based on input stream detection. Previously this only set the WSGI keys.
WSGIEnvironment
Returns a request with the data. If the request class is not specified request_class is used.
cls (Optional[Type[werkzeug.wrappers.request.Request]]) – The request wrapper to use.
werkzeug.wrappers.request.Request


Closes all files. If you put real file objects into the files dict you can call this method to automatically close them all in one go.
None


Turn an environ dict back into a builder. Any extra kwargs override the args extracted from the environ.
Changed in version 2.0: Path and query values are passed through the WSGI decoding dance to avoid double encoding.
New in version 0.15.
EnvironBuilder


Return the built environ.
Changed in version 0.15: The content type and length headers are set based on input stream detection. Previously this only set the WSGI keys.
WSGIEnvironment


Returns a request with the data. If the request class is not specified request_class is used.
cls (Optional[Type[werkzeug.wrappers.request.Request]]) – The request wrapper to use.
werkzeug.wrappers.request.Request


The serialization function used when json is passed.


the server protocol to use. defaults to HTTP/1.1


the wsgi version to use. defaults to (1, 0)


Read only version of the headers from a WSGI environment. This provides the same interface as Headers and is constructed from a WSGI environment.
From Werkzeug 0.3 onwards, the KeyError raised by this class is also a subclass of the BadRequest HTTP exception and will render a page for a 400 BAD REQUEST if caught in a catch-all for HTTP exceptions.


Maps request attributes to environment variables. This works not only for the Werkzeug request object, but also any other class with an environ attribute:
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.


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.
s (Any) –
str


A set that can be used to check if one etag is present in a collection of etags.
Convert the ETags object into a python set. Per default all the weak etags are not part of this set.
Check if an etag is part of the set ignoring weak tags. It is also possible to use the in operator.
When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only.
Check if an etag is part of the set including weak and strong tags.
Check if an etag is strong.
Check if an etag is weak.
Convert the etags set into a HTTP header string.


Convert the ETags object into a python set. Per default all the weak etags are not part of this set.


Check if an etag is part of the set ignoring weak tags. It is also possible to use the in operator.


When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only.


Check if an etag is part of the set including weak and strong tags.


Convert the etags set into a HTTP header string.


Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a string. The URLs might also be IRIs.
If the path info could not be determined, None is returned.
Some examples:
Instead of providing a base URL you can also pass a WSGI environment.
Optional[str]
Changed in version 0.15: The errors parameter defaults to leaving invalid bytes quoted instead of replacing them.
New in version 0.6.


A very popular deployment setup on servers like lighttpd and nginx is FastCGI. To use your WSGI application with any of them you will need a FastCGI server first.
The most popular one is flup which we will use for this guide. Make sure to have it installed.
First you need to create the FastCGI server file. Let’s call it yourapplication.fcgi:
This is enough for Apache to work, however ngingx and older versions of lighttpd need a socket to be explicitly passed to communicate with the FastCGI server. For that to work you need to pass the path to the socket to the WSGIServer:
The path has to be the exact same path you define in the server config.
Save the yourapplication.fcgi file somewhere you will find it again. It makes sense to have that in /var/www/yourapplication or something similar.
Make sure to set the executable bit on that file so that the servers can execute it:
A basic FastCGI configuration for lighttpd looks like this:
Remember to enable the FastCGI, alias and rewrite modules. This configuration binds the application to /yourapplication.
See the Lighty docs for more information on FastCGI and Python.
Installing FastCGI applications on nginx is a bit tricky because by default some FastCGI parameters are not properly forwarded.
A basic FastCGI configuration for nginx looks like this:
This configuration binds the application to /yourapplication. If you want to have it in the URL root it’s a bit easier because you don’t have to figure out how to calculate PATH_INFO and SCRIPT_NAME:
Since Nginx doesn’t load FastCGI apps, you have to do it by yourself. You can either write an init.d script for that or execute it inside a screen session:
FastCGI deployments tend to be hard to debug on most webservers. Very often the only thing the server log tells you is something along the lines of “premature end of headers”. In order to debug the application the only thing that can really give you ideas why it breaks is switching to the correct user and executing the application by hand.
This example assumes your application is called application.fcgi and that your webserver user is www-data:
In this case the error seems to be “yourapplication” not being on the python path. Common problems are:


A special MultiDict that has convenience methods to add files to it. This is used for EnvironBuilder and generally useful for unittesting.
New in version 0.5.
Adds a new file to the dict. file can be a file name or a file-like or a FileStorage object.


Adds a new file to the dict. file can be a file name or a file-like or a FileStorage object.


The FileStorage class is a thin wrapper over incoming files. It is used by the request object to represent uploaded files. All the attributes of the wrapper stream are proxied by the file storage so it’s possible to do storage.read() instead of the long form storage.stream.read().
The input stream for the uploaded file. This usually points to an open temporary file.
The filename of the file on the client.
The name of the form field.
The multipart headers as Headers object. This usually contains irrelevant information but in combination with custom multipart requests the raw headers might be interesting.
New in version 0.6.
Close the underlying file if possible.
The content-length sent in the header. Usually not available
The content-type sent in the header. Usually not available
Like content_type, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type is text/HTML; charset=utf-8 the mimetype would be 'text/html'.
New in version 0.7.
The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.
New in version 0.7.
Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB.
For secure file saving also have a look at secure_filename().
Changed in version 1.0: Supports pathlib.


The multipart headers as Headers object. This usually contains irrelevant information but in combination with custom multipart requests the raw headers might be interesting.
New in version 0.6.


Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB.
For secure file saving also have a look at secure_filename().
Changed in version 1.0: Supports pathlib.


The input stream for the uploaded file. This usually points to an open temporary file.


This class can be used to convert a file-like object into an iterable. It yields buffer_size blocks until the file is fully read.
You should not use this class directly but rather use the wrap_file() function that uses the WSGI server’s file wrapper support if it’s available.
New in version 0.5.
If you’re using this object together with a Response you have to use the direct_passthrough mode.
None


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.
generator
Iterator[str]


This converter only accepts floating point values:
By default it only accepts unsigned, positive values. The signed parameter will enable signed, negative values.
None
New in version 0.15: The signed parameter.


This class implements parsing of form data for Werkzeug. By itself it can parse multipart and url encoded form data. It can be subclassed and extended but for most mimetypes it is a better idea to use the untouched stream and expose it as separate attributes on a request object.
New in version 0.8.
None


Generate an etag for some data.
Changed in version 2.0: Use SHA-1. MD5 may not be available in some environments.
data (bytes) –
str


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:
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:
str


Returns the content length from the WSGI environment as integer. If it’s not available or chunked transfer encoding is used, None is returned.
New in version 0.9.
environ (WSGIEnvironment) – the WSGI environ to fetch the content length from.
Optional[int]


Recreate the URL for a request from the parts in a WSGI environment.
The URL is an IRI, not a URI, so it may contain Unicode characters. Use iri_to_uri() to convert it to ASCII.
str


Returns the filesystem encoding that should be used. Note that this is different from the Python understanding of the filesystem encoding which might be deeply flawed. Do not use this value against Python’s string APIs because it might be different. See The Filesystem for the exact behavior.
The concept of a filesystem encoding in generally is not something you should rely on. As such if you ever need to use this function except for writing wrapper code reconsider.
str


Return the host for the given WSGI environment.
The Host header is preferred, then SERVER_NAME if it’s not set. The returned host will only contain the port if it is different than the standard port for the protocol.
Optionally, verify that the host is trusted using host_is_trusted() and raise a SecurityError if it is not.
Host, with port if necessary.
SecurityError – If the host is not trusted.
str


Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length.
If content length is not set, the stream will be empty for safety reasons. If the WSGI server supports chunked or infinite streams, it should set the wsgi.input_terminated value in the WSGI environ to indicate that.
New in version 0.9.
BinaryIO


Return the PATH_INFO from the WSGI environment and decode it unless charset is None.
str
New in version 0.9.


Returns the QUERY_STRING from the WSGI environment. This also takes care of the WSGI decoding dance. The string returned will be restricted to ASCII characters.
environ (WSGIEnvironment) – WSGI environment to get the query string from.
str
New in version 0.9.


Return the SCRIPT_NAME from the WSGI environment and decode it unless charset is set to None.
str
New in version 0.9.


An object that stores some headers. It has a dict-like interface, but is ordered, can store the same key multiple times, and iterating yields (key, value) pairs instead of only keys.
This data structure is useful if you want a nicer way to handle WSGI headers which are stored as tuples in a list.
From Werkzeug 0.3 onwards, the KeyError raised by this class is also a subclass of the BadRequest HTTP exception and will render a page for a 400 BAD REQUEST if caught in a catch-all for HTTP exceptions.
Headers is mostly compatible with the Python wsgiref.headers.Headers class, with the exception of __getitem__. wsgiref will return None for headers['missing'], whereas Headers will raise a KeyError.
To create a new Headers object pass it a list or dict of headers which are used as default values. This does not reuse the list passed to the constructor for internal usage.
defaults – The list of default values for the Headers.
Changed in version 0.9: This data structure now stores unicode values similar to how the multi dicts do it. The main difference is that bytes can be set as well which will automatically be latin1 decoded.
Changed in version 0.9: The linked() function was removed without replacement as it was an API that does not support the changes to the encoding model.
Add a new header tuple to the list.
Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes:
The keyword argument dumping uses dump_options_header() behind the scenes.
New in version 0.4.1: keyword arguments were added for wsgiref compatibility.
Add a new header tuple to the list.
An alias for add() for compatibility with the wsgiref add_header() method.
Clears all headers.
Extend headers in this object with items from another object containing header items as well as keyword arguments.
To replace existing keys instead of extending, use update() instead.
If provided, the first argument can be another Headers object, a MultiDict, dict, or iterable of pairs.
Changed in version 1.0: Support MultiDict. Allow passing kwargs.
Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found:
New in version 0.9: Added support for as_bytes.
Return a list of all the values for the named field.
This method is compatible with the wsgiref get_all() method.
Return the list of items for a given key. If that key is not in the Headers, the return value will be an empty list. Just like get(), getlist() accepts a type parameter. All items will be converted with the callable defined there.
New in version 0.9: Added support for as_bytes.
a list of all the values for the key.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use key in data instead.
Removes and returns a key or index.
key – The key to be popped. If this is an integer the item at that position is removed, if it’s a string the value for that key is. If the key is omitted or None the last item is removed.
an item.
Removes a key or index and returns a (key, value) item.
Remove a key.
key – The key to be removed.
Remove all header tuples for key and add a new one. The newly added key either appears at the end of the list if there was no entry or replaces the first one.
Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes. See add() for more information.
Changed in version 0.6.1: set() now accepts the same arguments as add().
Return the first value for the key if it is in the headers, otherwise set the header to the value given by default and return that.
Remove any existing values for a header and add new ones.
New in version 1.0.
Return the list of values for the key if it is in the headers, otherwise set the header to the list of values given by default and return that.
Unlike MultiDict.setlistdefault(), modifying the returned list will not affect the headers.
New in version 1.0.
Convert the headers into a list suitable for WSGI.
list
Replace headers in this object with items from another headers object and keyword arguments.
To extend existing keys instead of replacing, use extend() instead.
If provided, the first argument can be another Headers object, a MultiDict, dict, or iterable of pairs.
New in version 1.0.


Add a new header tuple to the list.
Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes:
The keyword argument dumping uses dump_options_header() behind the scenes.
New in version 0.4.1: keyword arguments were added for wsgiref compatibility.


Add a new header tuple to the list.
An alias for add() for compatibility with the wsgiref add_header() method.


Extend headers in this object with items from another object containing header items as well as keyword arguments.
To replace existing keys instead of extending, use update() instead.
If provided, the first argument can be another Headers object, a MultiDict, dict, or iterable of pairs.
Changed in version 1.0: Support MultiDict. Allow passing kwargs.


Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found:
New in version 0.9: Added support for as_bytes.


Return the list of items for a given key. If that key is not in the Headers, the return value will be an empty list. Just like get(), getlist() accepts a type parameter. All items will be converted with the callable defined there.
New in version 0.9: Added support for as_bytes.
a list of all the values for the key.


Return a list of all the values for the named field.
This method is compatible with the wsgiref get_all() method.


Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use key in data instead.


Removes and returns a key or index.
key – The key to be popped. If this is an integer the item at that position is removed, if it’s a string the value for that key is. If the key is omitted or None the last item is removed.
an item.


Removes a key or index and returns a (key, value) item.


Remove a key.
key – The key to be removed.


Remove all header tuples for key and add a new one. The newly added key either appears at the end of the list if there was no entry or replaces the first one.
Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes. See add() for more information.
Changed in version 0.6.1: set() now accepts the same arguments as add().


Return the first value for the key if it is in the headers, otherwise set the header to the value given by default and return that.


Remove any existing values for a header and add new ones.
New in version 1.0.


Return the list of values for the key if it is in the headers, otherwise set the header to the list of values given by default and return that.
Unlike MultiDict.setlistdefault(), modifying the returned list will not affect the headers.
New in version 1.0.


Convert the headers into a list suitable for WSGI.
list


Replace headers in this object with items from another headers object and keyword arguments.
To extend existing keys instead of replacing, use extend() instead.
If provided, the first argument can be another Headers object, a MultiDict, dict, or iterable of pairs.
New in version 1.0.


Similar to the ETags class this implements a set-like structure. Unlike ETags this is case insensitive and used for vary, allow, and content-language headers.
If not constructed using the parse_set_header() function the instantiation works like this:
Add a new header to the set.
Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost.
preserve_casing – if set to True the items in the set returned will have the original case like in the HeaderSet, otherwise they will be lowercase.
Clear the set.
Like remove() but ignores errors.
header – the header to be discarded.
Return the index of the header in the set or return -1 if not found.
header – the header to be looked up.
Return the index of the header in the set or raise an IndexError.
header – the header to be looked up.
Remove a header from the set. This raises an KeyError if the header is not in the set.
Changed in version 0.5: In older versions a IndexError was raised instead of a KeyError if the object was missing.
header – the header to be removed.
Convert the header set into an HTTP header string.
Add all the headers from the iterable to the set.
iterable – updates the set with the items from the iterable.


Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost.
preserve_casing – if set to True the items in the set returned will have the original case like in the HeaderSet, otherwise they will be lowercase.


Like remove() but ignores errors.
header – the header to be discarded.


Return the index of the header in the set or return -1 if not found.
header – the header to be looked up.


Return the index of the header in the set or raise an IndexError.
header – the header to be looked up.


Remove a header from the set. This raises an KeyError if the header is not in the set.
Changed in version 0.5: In older versions a IndexError was raised instead of a KeyError if the object was missing.
header – the header to be removed.


Convert the header set into an HTTP header string.


Add all the headers from the iterable to the set.
iterable – updates the set with the items from the iterable.


Check if a host matches a list of trusted names.
bool
New in version 0.9.


Implements a callable that constructs URLs with the given base. The function can be called with any number of positional and keyword arguments which than are used to assemble the URL. Works with URLs and posix paths.
Positional arguments are appended as individual segments to the path of the URL:
If any of the arguments (positional or keyword) evaluates to None it will be skipped. If no keyword arguments are given the last argument can be a dict or MultiDict (or any other dict subclass), otherwise the keyword arguments are used for the query parameters, cutting off the first trailing underscore of the parameter name:
Combining of both methods is not allowed:
Accessing attributes on the href object creates a new href object with the attribute name as prefix:
If sort is set to True the items are sorted by key or the default sorting algorithm:
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use werkzeug.routing instead.
New in version 0.5: sort and key were added.


Helper object for HTML generation.
Per default there are two instances of that class. The html one, and the xhtml 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:
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:
Deprecated since version 2.0: Will be removed in Werkzeug 2.1.


Get a response object. If one was passed to the exception it’s returned directly.
a Response object or a subclass thereof.
Response


Call the exception as WSGI application.
Iterable[bytes]


Format a datetime object or timestamp into an RFC 2822 date string.
This is a wrapper for email.utils.format_datetime(). It assumes naive datetime objects are in UTC instead of raising an exception.
timestamp (Optional[Union[datetime.datetime, datetime.date, int, float, time.struct_time]]) – The datetime or timestamp to format. Defaults to the current time.
str
Changed in version 2.0: Use email.utils.format_datetime. Accept date objects.


Very simple object that represents the If-Range header in parsed form. It will either have neither a etag or date or one of either but never both.
New in version 0.7.
The date in parsed format or None.
The etag parsed and unquoted. Ranges always operate on strong etags so the weakness information is not necessary.
Converts the object back into an HTTP header.


The etag parsed and unquoted. Ranges always operate on strong etags so the weakness information is not necessary.


Converts the object back into an HTTP header.


An immutable dict.
New in version 0.5.
Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).


Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).


An immutable MultiDict.
New in version 0.5.
Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).


An immutable OrderedMultiDict.
New in version 0.6.
Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).


Works like a TypeConversionDict but does not support modifications.
New in version 0.5.
Return a shallow mutable copy of this object. Keep in mind that the standard library’s copy() function is a no-op for this class like for any other python immutable type (eg: tuple).


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.
imported object
Any


We recommend using the latest version of Python. Werkzeug supports Python 3.6 and newer.
Werkzeug does not have any direct dependencies.
These distributions will not be installed automatically. Werkzeug will detect and use them if you install them.
Use a virtual environment to manage the dependencies for your project, both in development and in production.
What problem does a virtual environment solve? The more Python projects you have, the more likely it is that you need to work with different versions of Python libraries, or even Python itself. Newer versions of libraries for one project can break compatibility in another project.
Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system’s packages.
Python comes bundled with the venv module to create virtual environments.
Create a project folder and a venv folder within:
On Windows:
Before you work on your project, activate the corresponding environment:
On Windows:
Your shell prompt will change to show the name of the activated environment.
Within the activated environment, use the following command to install Werkzeug:


This converter only accepts integer values:
By default it only accepts unsigned, positive values. The signed parameter will enable signed, negative values.
None
New in version 0.15: The signed parameter.


The original exception that caused this 500 error. Can be used by frameworks to provide context when handling unexpected errors.


Invalidates the cache for a cached_property:
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.
None


Convert an IRI to a URI. All non-ASCII and unsafe characters are quoted. If the URL has a domain, it is encoded to Punycode.
str
There is a general problem with IRI conversion with some protocols that are in violation of the URI specification. Consider the following two IRIs:
After parsing, we don’t know if the scheme requires the //, which is dropped if empty, but conveys different meanings in the final URL if it’s present or not. In this case, you can use safe_conversion, which will return the URL unchanged if it only contains ASCII characters and no whitespace. This can result in a URI with unquoted characters if it was not already quoted correctly, but preserves the URL’s semantics. Werkzeug uses this for the Location header for redirects.
Changed in version 0.15: All reserved characters remain unquoted. Previously, only some reserved characters were left unquoted.
Changed in version 0.9.6: The safe_conversion parameter was added.
New in version 0.6.


Checks if a given byte content range is valid for the given length.
New in version 0.7.
bool


Check if a header is an entity header.
New in version 0.5.
header (str) – the header to test.
True if it’s an entity header, False otherwise.
bool


Check if a header is an HTTP/1.1 “Hop-by-Hop” header.
New in version 0.5.
header (str) – the header to test.
True if it’s an HTTP/1.1 “Hop-by-Hop” header, False otherwise.
bool


Convenience method for conditional requests.
True if the resource was modified, otherwise False.
bool
Changed in version 2.0: SHA-1 is used to generate an etag value for the data. MD5 may not be available in some environments.
Changed in version 1.0.0: The check is run for methods other than GET and HEAD.


Checks if the application is running from within the Werkzeug reloader subprocess.
New in version 0.10.
bool


Like Accept but with normalization for language tags.


Wraps a stream so that it doesn’t read more than n bytes. If the stream is exhausted and the caller tries to get more bytes from it on_exhausted() is called which by default returns an empty string. The return value of that function is forwarded to the reader function. So if it returns an empty string read() will return an empty string as well.
The limit however must never be higher than what the stream can output. Otherwise readlines() will try to read past the limit.
Note on WSGI compliance
calls to readline() and readlines() are not WSGI compliant because it passes a size argument to the readline methods. Unfortunately the WSGI PEP is not safely implementable without a size argument to readline() because there is no EOF marker in the stream. As a result of that the use of readline() is discouraged.
For the same reason iterating over the LimitedStream is not portable. It internally calls readline().
We strongly suggest using read() only or using the make_line_iter() which safely iterates line-based over a WSGI input stream.
None
Exhaust the stream. This consumes all the data left until the limit is reached.
chunk_size (int) – the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results.
None
If the stream is exhausted this attribute is True.
What should happen if a disconnect is detected? The return value of this function is returned from read functions in case the client went away. By default a ClientDisconnected exception is raised.
bytes
This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function.
bytes
Read size bytes or if size is not provided everything is read.
size (Optional[int]) – the number of bytes read.
bytes
Return whether object was opened for reading.
If False, read() will raise OSError.
bool
Reads one line from the stream.
size (Optional[int]) –
bytes
Reads a file into a list of strings. It calls readline() until the file is read to the end. It does support the optional size argument if the underlying stream supports it for readline.
size (Optional[int]) –
List[bytes]
Returns the position of the stream.
New in version 0.9.
int


Exhaust the stream. This consumes all the data left until the limit is reached.
chunk_size (int) – the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results.
None


What should happen if a disconnect is detected? The return value of this function is returned from read functions in case the client went away. By default a ClientDisconnected exception is raised.
bytes


This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function.
bytes


Read size bytes or if size is not provided everything is read.
size (Optional[int]) – the number of bytes read.
bytes


Return whether object was opened for reading.
If False, read() will raise OSError.
bool


Reads one line from the stream.
size (Optional[int]) –
bytes


Reads a file into a list of strings. It calls readline() until the file is read to the end. It does support the optional size argument if the underlying stream supports it for readline.
size (Optional[int]) –
List[bytes]


Returns the position of the stream.
New in version 0.9.
int


Warns about common errors in the WSGI and HTTP behavior of the server and wrapped application. Some of the issues it checks are:
Error information is emitted using the warnings module.
app (WSGIApplication) – The WSGI application to wrap.
None


Local objects cannot manage themselves. For that you need a local manager. You can pass a local manager multiple locals or add them later y appending them to manager.locals. Every time the manager cleans up, it will clean up all the data left in the locals for this context.
Changed in version 2.0: ident_func is deprecated and will be removed in Werkzeug 2.1.
Changed in version 0.7: The ident_func parameter was added.
Changed in version 0.6.1: The release_local() function can be used instead of a manager.
None
Manually clean up the data in the locals for this context. Call this at the end of the request or use make_middleware().
None
Return the context identifier the local objects use internally for this context. You cannot override this method to change the behavior but use it to link other context local objects (such as SQLAlchemy’s scoped sessions) to the Werkzeug locals.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1.
Changed in version 0.7: You can pass a different ident function to the local manager that will then be propagated to all the locals passed to the constructor.
int
Wrap a WSGI application so that cleaning up happens after request end.
app (WSGIApplication) –
WSGIApplication
Like make_middleware but for decorating functions.
Example usage:
The difference to make_middleware is that the function passed will have all the arguments copied from the inner application (name, docstring, module).
func (WSGIApplication) –
WSGIApplication


Manually clean up the data in the locals for this context. Call this at the end of the request or use make_middleware().
None


Return the context identifier the local objects use internally for this context. You cannot override this method to change the behavior but use it to link other context local objects (such as SQLAlchemy’s scoped sessions) to the Werkzeug locals.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1.
Changed in version 0.7: You can pass a different ident function to the local manager that will then be propagated to all the locals passed to the constructor.
int


Wrap a WSGI application so that cleaning up happens after request end.
app (WSGIApplication) –
WSGIApplication


Like make_middleware but for decorating functions.
Example usage:
The difference to make_middleware is that the function passed will have all the arguments copied from the inner application (name, docstring, module).
func (WSGIApplication) –
WSGIApplication


A proxy to the object bound to a Local. All operations on the proxy are forwarded to the bound object. If no object is bound, a RuntimeError is raised.
__repr__ and __class__ are forwarded, so repr(x) and isinstance(x, cls) will look like the proxied object. Use issubclass(type(x), LocalProxy) to check if an object is a proxy.
Changed in version 2.0: Updated proxied attributes and methods to reflect the current data model.
Changed in version 0.6.1: The class can be instantiated with a callable.
Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context.
Any


Return the current object. This is useful if you want the real object behind the proxy at a time for performance reasons or because you want to pass the object into a different context.
Any


This class works similar to a Local but keeps a stack of objects instead. This is best explained with an example:
They can be force released by using a LocalManager or with the release_local() function but the correct way is to pop the item from the stack after using. When the stack is empty it will no longer be bound to the current context (and as such released).
By calling the stack without arguments it returns a proxy that resolves to the topmost item on the stack.
New in version 0.6.1.
None
Removes the topmost item from the stack, will return the old value or None if the stack was already empty.
Any
Pushes a new item to the stack
obj (Any) –
List[Any]
The topmost item on the stack. If the stack is empty, None is returned.


Removes the topmost item from the stack, will return the old value or None if the stack was already empty.
Any


Pushes a new item to the stack
obj (Any) –
List[Any]


Works like make_line_iter() but accepts a separator which divides chunks. If you want newline based processing you should use make_line_iter() instead as it supports arbitrary newline markers.
New in version 0.11.10: added support for the cap_at_buffer parameter.
New in version 0.9: added support for iterators as input stream.
New in version 0.8.
Iterator[bytes]


Safely iterates line-based over an input stream. If the input stream is not a LimitedStream the limit parameter is mandatory.
This uses the stream’s read() method internally as opposite to the readline() method that is unsafe and can only be used in violation of the WSGI specification. The same problem applies to the __iter__ function of the input stream which calls readline() without arguments.
If you need line-by-line processing it’s strongly recommended to iterate over the input stream using this helper function.
New in version 0.11.10: added support for the cap_at_buffer parameter.
New in version 0.9: added support for iterators as input stream.
Changed in version 0.8: This function now ensures that the limit was reached.
Iterator[bytes]


Creates an SSL key for development. This should be used instead of the 'adhoc' key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it will use the CN *.host/CN=host.
For more information see run_simple().
New in version 0.9.
Tuple[str, str]


The map class stores all the URL rules and some configuration parameters. Some of the configuration values are only stored on the Map instance since those affect all rules, others are just defaults and can be overridden for each rule. Note that you have to specify all arguments besides the rules as keyword arguments!
None
Changed in version 1.0: If url_scheme is ws or wss, only WebSocket rules will match.
Changed in version 1.0: Added merge_slashes.
Changed in version 0.7: Added encoding_errors and host_matching.
Changed in version 0.5: Added sort_parameters and sort_key.
The dictionary of converters. This can be modified after the class was created, but will only affect rules added after the modification. If the rules are defined with the list passed to the class, the converters parameter to the constructor has to be used instead.
Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map.
rulefactory (werkzeug.routing.RuleFactory) – a Rule or RuleFactory
None
Return a new MapAdapter with the details specified to the call. Note that script_name will default to '/' if not further specified or None. The server_name at least is a requirement because the HTTP RFC requires absolute URLs for redirects and so all redirect exceptions raised by Werkzeug will contain the full canonical URL.
If no path_info is passed to match() it will use the default path info passed to bind. While this doesn’t really make sense for manual bind calls, it’s useful if you bind a map to a WSGI environment which already contains the path info.
subdomain will default to the default_subdomain for this map if no defined. If there is no default_subdomain you cannot use the subdomain feature.
Changed in version 1.0: If url_scheme is ws or wss, only WebSocket rules will match.
Changed in version 0.15: path_info defaults to '/' if None.
Changed in version 0.8: query_args can be a string.
Changed in version 0.7: Added query_args.
werkzeug.routing.MapAdapter
Like bind() but you can pass it an WSGI environment and it will fetch the information from that dictionary. Note that because of limitations in the protocol there is no way to get the current subdomain and real server_name from the environment. If you don’t provide it, Werkzeug will use SERVER_NAME and SERVER_PORT (or HTTP_HOST if provided) as used server_name with disabled subdomain feature.
If subdomain is None but an environment and a server name is provided it will calculate the current subdomain automatically. Example: server_name is 'example.com' and the SERVER_NAME in the wsgi environ is 'staging.dev.example.com' the calculated subdomain will be 'staging.dev'.
If the object passed as environ has an environ attribute, the value of this attribute is used instead. This allows you to pass request objects. Additionally PATH_INFO added as a default of the MapAdapter so that you don’t have to pass the path info to the match method.
Changed in version 1.0.0: If the passed server name specifies port 443, it will match if the incoming scheme is https without a port.
Changed in version 1.0.0: A warning is shown when the passed server name does not match the incoming WSGI server name.
Changed in version 0.8: This will no longer raise a ValueError when an unexpected server name was passed.
Changed in version 0.5: previously this method accepted a bogus calculate_subdomain parameter that did not have any effect. It was removed because of that.
MapAdapter
A dict of default converters to be used.
Iterate over all rules and check if the endpoint expects the arguments provided. This is for example useful if you have some URLs that expect a language code and others that do not and you want to wrap the builder a bit so that the current language code is automatically added if not provided but endpoints expect it.
bool
Iterate over all rules or the rules of an endpoint.
endpoint (Optional[str]) – if provided only the rules for that endpoint are returned.
an iterator
Iterator[werkzeug.routing.Rule]
The type of lock to use when updating.
New in version 1.0.
Called before matching and building to keep the compiled rules in the correct order after things changed.
None


Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map.
rulefactory (werkzeug.routing.RuleFactory) – a Rule or RuleFactory
None


Return a new MapAdapter with the details specified to the call. Note that script_name will default to '/' if not further specified or None. The server_name at least is a requirement because the HTTP RFC requires absolute URLs for redirects and so all redirect exceptions raised by Werkzeug will contain the full canonical URL.
If no path_info is passed to match() it will use the default path info passed to bind. While this doesn’t really make sense for manual bind calls, it’s useful if you bind a map to a WSGI environment which already contains the path info.
subdomain will default to the default_subdomain for this map if no defined. If there is no default_subdomain you cannot use the subdomain feature.
Changed in version 1.0: If url_scheme is ws or wss, only WebSocket rules will match.
Changed in version 0.15: path_info defaults to '/' if None.
Changed in version 0.8: query_args can be a string.
Changed in version 0.7: Added query_args.
werkzeug.routing.MapAdapter


Like bind() but you can pass it an WSGI environment and it will fetch the information from that dictionary. Note that because of limitations in the protocol there is no way to get the current subdomain and real server_name from the environment. If you don’t provide it, Werkzeug will use SERVER_NAME and SERVER_PORT (or HTTP_HOST if provided) as used server_name with disabled subdomain feature.
If subdomain is None but an environment and a server name is provided it will calculate the current subdomain automatically. Example: server_name is 'example.com' and the SERVER_NAME in the wsgi environ is 'staging.dev.example.com' the calculated subdomain will be 'staging.dev'.
If the object passed as environ has an environ attribute, the value of this attribute is used instead. This allows you to pass request objects. Additionally PATH_INFO added as a default of the MapAdapter so that you don’t have to pass the path info to the match method.
Changed in version 1.0.0: If the passed server name specifies port 443, it will match if the incoming scheme is https without a port.
Changed in version 1.0.0: A warning is shown when the passed server name does not match the incoming WSGI server name.
Changed in version 0.8: This will no longer raise a ValueError when an unexpected server name was passed.
Changed in version 0.5: previously this method accepted a bogus calculate_subdomain parameter that did not have any effect. It was removed because of that.
MapAdapter


The dictionary of converters. This can be modified after the class was created, but will only affect rules added after the modification. If the rules are defined with the list passed to the class, the converters parameter to the constructor has to be used instead.


A dict of default converters to be used.


Iterate over all rules and check if the endpoint expects the arguments provided. This is for example useful if you have some URLs that expect a language code and others that do not and you want to wrap the builder a bit so that the current language code is automatically added if not provided but endpoints expect it.
bool


Iterate over all rules or the rules of an endpoint.
endpoint (Optional[str]) – if provided only the rules for that endpoint are returned.
an iterator
Iterator[werkzeug.routing.Rule]


The type of lock to use when updating.
New in version 1.0.


Called before matching and building to keep the compiled rules in the correct order after things changed.
None


Returned by Map.bind() or Map.bind_to_environ() and does the URL matching and building based on runtime information.
Returns the valid methods that match for a given path.
New in version 0.7.
path_info (Optional[str]) –
Iterable[str]
Building URLs works pretty much the other way round. Instead of match you call build and pass it the endpoint and a dict of arguments for the placeholders.
The build function also accepts an argument called force_external which, if you set it to True will force external URLs. Per default external URLs (include the server name) will only be used if the target URL is on a different subdomain.
Because URLs cannot contain non ASCII data you will always get bytes back. Non ASCII characters are urlencoded with the charset defined on the map instance.
Additional values are converted to strings and appended to the URL as URL querystring parameters:
When processing those additional values, lists are furthermore interpreted as multiple values (as per werkzeug.datastructures.MultiDict):
Passing a MultiDict will also add multiple values:
If a rule does not exist when building a BuildError exception is raised.
The build method accepts an argument called method which allows you to specify the method you want to have an URL built for if you have different methods for the same endpoint specified.
str
Changed in version 2.0: Added the url_scheme parameter.
New in version 0.6: Added the append_unknown parameter.
Does the complete dispatching process. view_func is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can display nicer error messages by just catching them by hand. If you want to stick with the default error messages you can pass it catch_http_exceptions=True and it will catch the http exceptions.
Here a small example for the dispatch usage:
Keep in mind that this method might return exception objects, too, so use Response.force_type to get a response object.
WSGIApplication
Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name.
domain_part (Optional[str]) –
str
Internally called to make an alias redirect URL.
str
The usage is simple: you just pass the match method the current path info as well as the method (which defaults to GET). The following things can then happen:
If the path info is not passed to the match method the default path info of the map is used (defaults to the root URL if not defined explicitly).
All of the exceptions raised are subclasses of HTTPException so they can be used as WSGI responses. They will all render generic error or redirect pages.
Here is a small example for matching:
And here is what happens on redirect and missing URLs:
Tuple[Union[str, werkzeug.routing.Rule], Mapping[str, Any]]
New in version 1.0: Added websocket.
Changed in version 0.8: query_args can be a string.
New in version 0.7: Added query_args.
New in version 0.6: Added return_rule.
Test if a rule would match. Works like match but returns True if the URL matches, or False if it does not exist.
bool


Returns the valid methods that match for a given path.
New in version 0.7.
path_info (Optional[str]) –
Iterable[str]


Building URLs works pretty much the other way round. Instead of match you call build and pass it the endpoint and a dict of arguments for the placeholders.
The build function also accepts an argument called force_external which, if you set it to True will force external URLs. Per default external URLs (include the server name) will only be used if the target URL is on a different subdomain.
Because URLs cannot contain non ASCII data you will always get bytes back. Non ASCII characters are urlencoded with the charset defined on the map instance.
Additional values are converted to strings and appended to the URL as URL querystring parameters:
When processing those additional values, lists are furthermore interpreted as multiple values (as per werkzeug.datastructures.MultiDict):
Passing a MultiDict will also add multiple values:
If a rule does not exist when building a BuildError exception is raised.
The build method accepts an argument called method which allows you to specify the method you want to have an URL built for if you have different methods for the same endpoint specified.
str
Changed in version 2.0: Added the url_scheme parameter.
New in version 0.6: Added the append_unknown parameter.


Does the complete dispatching process. view_func is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can display nicer error messages by just catching them by hand. If you want to stick with the default error messages you can pass it catch_http_exceptions=True and it will catch the http exceptions.
Here a small example for the dispatch usage:
Keep in mind that this method might return exception objects, too, so use Response.force_type to get a response object.
WSGIApplication


Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name.
domain_part (Optional[str]) –
str


Internally called to make an alias redirect URL.
str


The usage is simple: you just pass the match method the current path info as well as the method (which defaults to GET). The following things can then happen:
If the path info is not passed to the match method the default path info of the map is used (defaults to the root URL if not defined explicitly).
All of the exceptions raised are subclasses of HTTPException so they can be used as WSGI responses. They will all render generic error or redirect pages.
Here is a small example for matching:
And here is what happens on redirect and missing URLs:
Tuple[Union[str, werkzeug.routing.Rule], Mapping[str, Any]]
New in version 1.0: Added websocket.
Changed in version 0.8: query_args can be a string.
New in version 0.7: Added query_args.
New in version 0.6: Added return_rule.


Test if a rule would match. Works like match but returns True if the URL matches, or False if it does not exist.
bool


A WSGI middleware is a WSGI application that wraps another application in order to observe or change its behavior. Werkzeug provides some middleware for common use cases.
The interactive debugger is also a middleware that can be applied manually, although it is typically used automatically with the development server.


Like Accept but with special methods and behavior for mimetypes.
True if this object accepts HTML.
True if this object accepts JSON.
True if this object accepts XHTML.


A MultiDict is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form elements pass multiple values for the same key.
MultiDict implements all standard dictionary methods. Internally, it saves all values for a key as a list, but the standard dict access methods will only return the first value for a key. If you want to gain access to the other values, too, you have to use the list methods as explained below.
Basic Usage:
It behaves like a normal dict thus all dict functions will only return the first value when multiple values for one key are found.
From Werkzeug 0.3 onwards, the KeyError raised by this class is also a subclass of the BadRequest HTTP exception and will render a page for a 400 BAD REQUEST if caught in a catch-all for HTTP exceptions.
A MultiDict can be constructed from an iterable of (key, value) tuples, a dict, a MultiDict or from Werkzeug 0.2 onwards some keyword parameters.
mapping – the initial value for the MultiDict. Either a regular dict, an iterable of (key, value) tuples or None.
Adds a new value for the key.
New in version 0.6.
Return a shallow copy of this object.
Return a deep copy of this object.
Create a new dictionary with keys from iterable and values set to value.
Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found:
Return the list of items for a given key. If that key is not in the MultiDict, the return value will be an empty list. Just like get, getlist accepts a type parameter. All items will be converted with the callable defined there.
a list of all the values for the key.
Return an iterator of (key, value) pairs.
multi – If set to True the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key.
Return a iterator of (key, values) pairs, where values is the list of all values associated with the key.
Return an iterator of all values associated with a key. Zipping keys() and this is the same as calling lists():
Pop the first item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded:
Pop an item from the dict.
Pop a (key, list) tuple from the dict.
Pop the list for a key from the dict. If the key is not in the dict an empty list is returned.
Changed in version 0.5: If the key does no longer exist a list is returned instead of raising an error.
Returns the value for the key if it is in the dict, otherwise it returns default and sets that value for key.
Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary.
Like setdefault but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list:
a list
Return the contents as regular dict. If flat is True the returned dict will only have the first item present, if flat is False all values will be returned as lists.
flat – If set to False the dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key.
a dict
update() extends rather than replaces existing key lists:
If the value list for a key in other_dict is empty, no new values will be added to the dict and the key will not be created:
Returns an iterator of the first value on every key’s value list.


Adds a new value for the key.
New in version 0.6.


Create a new dictionary with keys from iterable and values set to value.


Return the default value if the requested data doesn’t exist. If type is provided and is a callable it should convert the value, return it or raise a ValueError if that is not possible. In this case the function will return the default as if the value was not found:


Return the list of items for a given key. If that key is not in the MultiDict, the return value will be an empty list. Just like get, getlist accepts a type parameter. All items will be converted with the callable defined there.
a list of all the values for the key.


Return an iterator of (key, value) pairs.
multi – If set to True the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key.


Return a iterator of (key, values) pairs, where values is the list of all values associated with the key.


Return an iterator of all values associated with a key. Zipping keys() and this is the same as calling lists():


Pop the first item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded:


Pop the list for a key from the dict. If the key is not in the dict an empty list is returned.
Changed in version 0.5: If the key does no longer exist a list is returned instead of raising an error.


Returns the value for the key if it is in the dict, otherwise it returns default and sets that value for key.


Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary.


Like setdefault but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list:
a list


Return the contents as regular dict. If flat is True the returned dict will only have the first item present, if flat is False all values will be returned as lists.
flat – If set to False the dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key.
a dict


update() extends rather than replaces existing key lists:
If the value list for a key in other_dict is empty, no new values will be added to the dict and the key will not be created:


Returns an iterator of the first value on every key’s value list.


Works like a regular MultiDict but preserves the order of the fields. To convert the ordered multi dict into a list you can use the items() method and pass it multi=True.
In general an OrderedMultiDict is an order of magnitude slower than a MultiDict.
note
Due to a limitation in Python you cannot convert an ordered multi dict into a regular dict by using dict(multidict). Instead you have to use the to_dict() method, otherwise the internal bucket objects are exposed.


Parses an HTTP Accept-* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction.
Returns a new Accept object (basically a list of (value, quality) tuples sorted by the quality with some additional accessor methods).
The second parameter can be a subclass of Accept that is created with the parsed values and returned.
an instance of cls.
werkzeug.http._TAnyAccept


Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either None if the header was invalid or not given, otherwise an Authorization object.
value (Optional[str]) – the authorization header to parse.
a Authorization object or None.
Optional[werkzeug.datastructures.Authorization]


Parse a cache control header. The RFC differs between response and request cache control, this method does not. It’s your responsibility to not use the wrong control statements.
New in version 0.5: The cls was added. If not specified an immutable RequestCacheControl is returned.
a cls object.
werkzeug.http._TAnyCC


Parses a range header into a ContentRange object or None if parsing is not possible.
New in version 0.7.
Optional[werkzeug.datastructures.ContentRange]


Parse a cookie from a string or WSGI environ.
The same key can be provided multiple times, the values are stored in-order. The default MultiDict will have the first value first, and all values can be retrieved with MultiDict.getlist().
ds.MultiDict[str, str]
Changed in version 1.0.0: Returns a MultiDict instead of a TypeConversionDict.
Changed in version 0.5: Returns a TypeConversionDict instead of a regular dict. The cls parameter was added.


Parse an RFC 2822 date into a timezone-aware datetime.datetime object, or None if parsing fails.
This is a wrapper for email.utils.parsedate_to_datetime(). It returns None if parsing fails instead of raising an exception, and always returns a timezone-aware datetime object. If the string doesn’t have timezone information, it is assumed to be UTC.
value (Optional[str]) – A string with a supported date format.
Optional[datetime.datetime]
Changed in version 2.0: Return a timezone-aware datetime object. Use email.utils.parsedate_to_datetime.


Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the cls argument):
If there is no value for a key it will be None:
To create a header from the dict again, use the dump_header() function.
Changed in version 0.9: Added support for cls argument.
an instance of cls
Dict[str, str]


Parse an etag header.
value (Optional[str]) – the tag header to parse
an ETags object.
werkzeug.datastructures.ETags


Parse the form data in the environ and return it as tuple in the form (stream, form, files). You should only call this method if the transport method is POST, PUT, or PATCH.
If the mimetype of the data transmitted is multipart/form-data the files multidict will be filled with FileStorage objects. If the mimetype is unknown the input stream is wrapped and returned as first argument, else the stream is empty.
This is a shortcut for the common usage of FormDataParser.
Have a look at Dealing with Request Data for more details.
New in version 0.5.1: The optional silent flag was added.
New in version 0.5: The max_form_memory_size, max_content_length and cls parameters were added.
A tuple in the form (stream, form, files).
t_parse_result


Parses an if-range header which can be an etag or a date. Returns a IfRange object.
Changed in version 2.0: If the value represents a datetime, it is timezone-aware.
New in version 0.7.
value (Optional[str]) –
werkzeug.datastructures.IfRange


Parse lists as described by RFC 2068 Section 2.
In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing.
It basically works like parse_set_header() just that items may appear multiple times and case sensitivity is preserved.
The return value is a standard list:
To create a header from the list again, use the dump_header() function.
value (str) – a string with a list header.
list
List[str]


Parse a Content-Type like header into a tuple with the content type and the options:
This should not be used to parse Cache-Control like headers that use a slightly different format. For these headers use the parse_dict_header() function.
Changed in version 0.15: RFC 2231 parameter continuations are handled.
New in version 0.5.
(mimetype, options) or (mimetype, options, mimetype, options, …) if multiple=True
Union[Tuple[str, Dict[str, str]], Tuple[Any, …]]


Parses a range header into a Range object. If the header is missing or malformed None is returned. ranges is a list of (start, stop) tuples where the ranges are non-inclusive.
New in version 0.7.
Optional[werkzeug.datastructures.Range]


Parse a set-like header and return a HeaderSet object:
The return value is an object that treats the items case-insensitively and keeps the order of the items:
To create a header from the HeaderSet again, use the dump_header() function.
a HeaderSet
werkzeug.datastructures.HeaderSet


Parse an HTTP WWW-Authenticate header into a WWWAuthenticate object.
a WWWAuthenticate object.
werkzeug.datastructures.WWWAuthenticate


Like the default UnicodeConverter, but it also matches slashes. This is useful for wikis and similar applications:
None


Returns a binary digest for the PBKDF2 hash algorithm of data with the given salt. It iterates iterations times and produces a key of keylen bytes. By default, SHA-256 is used as hash function; a different hashlib hashfunc can be provided.
bytes
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use hashlib.pbkdf2_hmac() instead.
New in version 0.9.


Like pbkdf2_bin(), but returns a hex-encoded string.
str
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Use hashlib.pbkdf2_hmac() instead.
New in version 0.9.


Returns the next segment on the PATH_INFO or None if there is none. Works like pop_path_info() without modifying the environment:
If the charset is set to None bytes are returned.
Changed in version 0.9: The path is now decoded and a charset and encoding parameter can be provided.
New in version 0.5.
Optional[str]


Removes and returns the next segment of PATH_INFO, pushing it onto SCRIPT_NAME. Returns None if there is nothing left on PATH_INFO.
If the charset is set to None bytes are returned.
If there are empty segments ('/foo//bar) these are ignored but properly pushed to the SCRIPT_NAME:
Changed in version 0.9: The path is now decoded and a charset and encoding parameter can be provided.
New in version 0.5.
Optional[str]


Wrap a WSGI application and profile the execution of each request. Responses are buffered so that timings are more exact.
If stream is given, pstats.Stats are written to it after each request. If profile_dir is given, cProfile data files are saved to that directory, one file per request.
The filename can be customized by passing filename_format. If it is a string, it will be formatted using str.format() with the following fields available:
If it is a callable, it will be called with the WSGI environ dict and should return a filename.
None
Changed in version 0.15: Stats are written even if profile_dir is given, and can be disable by passing stream=None.
New in version 0.15: Added filename_format.
New in version 0.9: Added restrictions and profile_dir.


Adjust the WSGI environ based on X-Forwarded- that proxies in front of the application may set.
You must tell the middleware how many proxies set each header so it knows what values to trust. It is a security issue to trust values that came from the client rather than a proxy.
The original values of the headers are stored in the WSGI environ as werkzeug.proxy_fix.orig, a dict.
None
Changed in version 1.0: Deprecated code has been removed:
Changed in version 0.15: All headers support multiple values. The num_proxies argument is deprecated. Each header is configured with a separate number of trusted proxies.
Changed in version 0.15: Original WSGI environ values are stored in the werkzeug.proxy_fix.orig dict. orig_remote_addr, orig_wsgi_url_scheme, and orig_http_host are deprecated and will be removed in 1.0.
Changed in version 0.15: Support X-Forwarded-Port and X-Forwarded-Prefix.
Changed in version 0.15: X-Forwarded-Host and X-Forwarded-Port modify SERVER_NAME and SERVER_PORT.


Proxy requests under a path to an external server, routing other requests to the app.
This middleware can only proxy HTTP requests, as HTTP is the only protocol handled by the WSGI server. Other protocols, such as WebSocket requests, cannot be proxied at this layer. This should only be used for development, in production a real proxy server should be used.
The middleware takes a dict mapping a path prefix to a dict describing the host to be proxied to:
Each host has the following options:
The target URL to dispatch to. This is required.
Whether to remove the prefix from the URL before dispatching it to the target. The default is False.
The host header is automatically rewritten to the URL of the target.
The host header is unmodified from the client request.
The host header is overwritten with the value.
A dictionary of headers to be sent with the request to the target. The default is {}.
A ssl.SSLContext defining how to verify requests if the target is HTTPS. The default is None.
In the example above, everything under "/static/" is proxied to the server on port 5001. The host header is rewritten to the target, and the "/static/" prefix is removed from the URLs.
None
New in version 0.14.


This part of the documentation shows how to use the most important parts of Werkzeug. It’s intended as a starting point for developers with basic understanding of PEP 3333 (WSGI) and RFC 2616 (HTTP).


Quote a header value if necessary.
New in version 0.5.
str


Represents a Range header. All methods only support only bytes as the unit. Stores a list of ranges if given, but the methods only work if only one range is provided.
ValueError – If the ranges provided are invalid.
Changed in version 0.15: The ranges passed in are validated.
New in version 0.7.
Creates a ContentRange object from the current range and given content length.
If the range is for bytes, the length is not None and there is exactly one range and it is satisfiable it returns a (start, stop) tuple, otherwise None.
A list of (begin, end) tuples for the range header provided. The ranges are non-inclusive.
Converts the object into Content-Range HTTP header, based on given length
Converts the object back into an HTTP header.
The units of this range. Usually “bytes”.


Creates a ContentRange object from the current range and given content length.


A list of (begin, end) tuples for the range header provided. The ranges are non-inclusive.


If the range is for bytes, the length is not None and there is exactly one range and it is satisfiable it returns a (start, stop) tuple, otherwise None.


Converts the object into Content-Range HTTP header, based on given length


Converts the object back into an HTTP header.


The units of this range. Usually “bytes”.


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


Releases the contents of the local for the current context. This makes it possible to use locals without a manager.
Example:
With this function one can release Local objects as well as LocalStack objects. However it is not possible to release data held by proxies that way, one always has to retain a reference to the underlying local object in order to be able to release it.
New in version 0.6.1.
local (Union[werkzeug.local.Local, werkzeug.local.LocalStack]) –
None


Remove all entity headers from a list or Headers object. This operation works in-place. Expires and Content-Location headers are by default not removed. The reason for this is RFC 2616 section 10.3.5 which specifies some entity headers that should be sent.
Changed in version 0.5: added allowed parameter.
None


Remove all HTTP/1.1 “Hop-by-Hop” headers from a list or Headers object. This operation works in-place.
New in version 0.5.
headers (Union[werkzeug.datastructures.Headers, List[Tuple[str, str]]]) – a list or Headers object.
None


Represents an incoming WSGI HTTP request, with headers and body taken from the WSGI environment. Has properties and methods for using the functionality defined by various HTTP specs. The data in requests object is read-only.
Text data is assumed to use UTF-8 encoding, which should be true for the vast majority of modern clients. Using an encoding set by the client is unsafe in Python due to extra encodings it provides, such as zip. To change the assumed encoding, subclass and replace charset.
None
Changed in version 2.0: Combine BaseRequest and mixins into a single Request class. Using the old classes is deprecated and will be removed in Werkzeug 2.1.
Changed in version 0.5: Read-only mode is enforced with immutable classes for all data.
Called to get a stream for the file upload.
This must provide a file-like class with read(), readline() and seek() methods that is both writeable and readable.
The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters.
BinaryIO
List of charsets this client supports as CharsetAccept object.
List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at accept_charset.
List of languages this client accepts as LanguageAccept object.
List of mimetypes this client supports as MIMEAccept object.
Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set access_control_allow_headers on the response to indicate which headers are allowed.
Sent with a preflight request to indicate which method will be used for the cross origin request. Set access_control_allow_methods on the response to indicate which methods are allowed.
If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server.
Decorate a function as responder that accepts the request as the last argument. This works like the responder() decorator but the function is passed the request object as the last argument and the request object will be closed automatically:
As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing.
f (Callable[[Request], WSGIApplication]) – the WSGI callable to decorate
a new WSGI callable
WSGIApplication
The parsed URL parameters (the part in the URL after the question mark).
By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important.
The Authorization object in parsed form.
Like url but without the query string.
A RequestCacheControl object for the incoming cache control headers.
Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it.
New in version 0.9.
None
The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.
New in version 0.9.
The Content-Length entity-header field indicates the size of the entity-body in bytes or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.
The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)
New in version 0.9.
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.
A dict with the contents of all cookies transmitted with the request.
Contains the incoming request data as string in case it came with a mimetype Werkzeug does not handle.
The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822.
Changed in version 2.0: The datetime object is timezone-aware.
alias of werkzeug.datastructures.ImmutableMultiDict
Disable the data property to avoid reading from the input stream.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Create the request with shallow=True instead.
New in version 0.9.
The WSGI environment containing HTTP headers and information from the WSGI server.
MultiDict object containing all uploaded files. Each key in files is the name from the <input type="file" name="">. Each value in files is a Werkzeug FileStorage object.
It basically behaves like a standard file object you know from Python, with the difference that it also has a save() function that can store the file on the filesystem.
Note that files will only contain data if the request method was POST, PUT or PATCH and the <form> that posted to the request had enctype="multipart/form-data". It will be empty otherwise.
See the MultiDict / FileStorage documentation for more details about the used data structure.
The form parameters. By default an ImmutableMultiDict is returned from this function. This can be changed by setting parameter_storage_class to a different type. This might be necessary if the order of the form data is important.
Please keep in mind that file uploads will not end up here, but instead in the files attribute.
Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests.
alias of werkzeug.formparser.FormDataParser
Create a new request object based on the values provided. If environ is given missing values are filled from there. This method is useful for small scripts when you need to simulate a request from an URL. Do not use this method for unittesting, there is a full featured client object (Client) that allows to create multipart requests, support for cookies etc.
This accepts the same options as the EnvironBuilder.
Changed in version 0.5: This method now accepts the same arguments as EnvironBuilder. Because of this the environ parameter is now called environ_overrides.
request object
werkzeug.wrappers.request.Request
Requested path, including the query string.
This reads the buffered incoming data from the client into one bytes object. By default this is cached but that behavior can be changed by setting cache to False.
Usually it’s a bad idea to call this method without checking the content length first as a client could send dozens of megabytes or more to cause memory problems on the server.
Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set parse_form_data to True. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory.
If as_text is set to True the return value will be a decoded string.
New in version 0.9.
Union[bytes, str]
Parse data as JSON.
If the mimetype does not indicate JSON (application/json, see is_json()), this returns None.
If parsing fails, on_json_loading_failed() is called and its return value is used as the return value.
Optional[Any]
The headers received with the request.
The host name the request was made to, including the port if it’s non-standard. Validated with trusted_hosts.
The request URL scheme and host only.
An object containing all the etags in the If-Match header.
ETags
The parsed If-Modified-Since header as a datetime object.
Changed in version 2.0: The datetime object is timezone-aware.
An object containing all the etags in the If-None-Match header.
ETags
The parsed If-Range header.
Changed in version 2.0: IfRange.date is timezone-aware.
New in version 0.7.
The parsed If-Unmodified-Since header as a datetime object.
Changed in version 2.0: The datetime object is timezone-aware.
The WSGI input stream.
In general it’s a bad idea to use this one because you can easily read past the boundary. Use the stream instead.
Check if the mimetype indicates JSON data, either application/json or application/*+json.
boolean that is True if the application is served by a WSGI server that spawns multiple processes.
boolean that is True if the application is served by a multithreaded WSGI server.
boolean that is True if the application will be executed only once in a process lifetime. This is the case for CGI for example, but it’s not guaranteed that the execution only happens one time.
True if the request was made with a secure protocol (HTTPS or WSS).
The parsed JSON data if mimetype indicates JSON (application/json, see is_json()).
Calls get_json() with default arguments.
A module or other object that has dumps and loads functions that match the API of the built-in json module.
alias of werkzeug.datastructures.ImmutableList
Creates the form data parser. Instantiates the form_data_parser_class with some parameters.
New in version 0.8.
werkzeug.formparser.FormDataParser
the maximum content length. This is forwarded to the form data parsing function (parse_form_data()). When set and the form or files attribute is accessed and the parsing fails because more than the specified value is transmitted a RequestEntityTooLarge exception is raised.
Have a look at Dealing with Request Data for more details.
New in version 0.5.
the maximum form field size. This is forwarded to the form data parsing function (parse_form_data()). When set and the form or files attribute is accessed and the data in memory for post data is longer than the specified value a RequestEntityTooLarge exception is raised.
Have a look at Dealing with Request Data for more details.
New in version 0.5.
The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server.
The method the request was made with, such as GET.
Like content_type, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type is text/HTML; charset=utf-8 the mimetype would be 'text/html'.
The mimetype parameters as dict. For example if the content type is text/html; charset=utf-8 the params would be {'charset': 'utf-8'}.
Called if get_json() parsing fails and isn’t silenced. If this method returns a value, it is used as the return value for get_json(). The default implementation raises BadRequest.
e (ValueError) –
Any
The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed.
alias of werkzeug.datastructures.ImmutableMultiDict
The path part of the URL after root_path. This is the path used for routing within the application.
The Pragma general-header field is used to include implementation-specific directives that might apply to any recipient along the request/response chain. All pragma directives specify optional behavior from the viewpoint of the protocol; however, some systems MAY require that behavior be consistent with the directives.
The part of the URL after the “?”. This is the raw value, use args for the parsed values.
The parsed Range header.
New in version 0.7.
Range
The Referer[sic] request-header field allows the client to specify, for the server’s benefit, the address (URI) of the resource from which the Request-URI was obtained (the “referrer”, although the header field is misspelled).
The address of the client sending the request.
If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as.
The prefix that the application is mounted under, without a trailing slash. path comes after this.
The request URL scheme, host, and root path. This is the root that the application is accessed from.
The URL scheme of the protocol the request used, such as https or wss.
Alias for self.root_path. environ["SCRIPT_ROOT"] without a trailing slash.
The address of the server. (host, port), (path, None) for unix sockets, or None if not known.
Set when creating the request object. If True, reading from the request body will cause a RuntimeException. Useful to prevent modifying the stream from middleware.
If the incoming form data was not encoded with a known mimetype the data is stored unmodified in this stream for consumption. Most of the time it is a better idea to use data which will give you that data as a string. The stream only returns the data once.
Unlike input_stream this stream is properly guarded that you can’t accidentally read past the length of the input. Werkzeug will internally always refer to this stream to read data which makes it possible to wrap this object with a stream that does filtering.
Changed in version 0.9: This stream is now always available but might be consumed by the form parser later on. Previously the stream was only set if no parsing happened.
The full request URL with the scheme, host, root path, path, and query string.
The charset that is assumed for URLs. Defaults to the value of charset.
New in version 0.6.
Alias for root_url. The URL with scheme, host, and root path. For example, https://example.com/app/.
The user agent. Use user_agent.string to get the header value. Set user_agent_class to a subclass of UserAgent to provide parsing for the other properties or other extended data.
Changed in version 2.0: The built in parser is deprecated and will be removed in Werkzeug 2.1. A UserAgent subclass must be set to parse data from the string.
alias of werkzeug.useragents._UserAgent
A werkzeug.datastructures.CombinedMultiDict that combines args and form.
For GET requests, only args are present, not form.
Changed in version 2.0: For GET requests, only args are present, not form.
True if the request method carries content. By default this is true if a Content-Type is sent.
New in version 0.8.


Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set access_control_allow_headers on the response to indicate which headers are allowed.


Sent with a preflight request to indicate which method will be used for the cross origin request. Set access_control_allow_methods on the response to indicate which methods are allowed.


Decorate a function as responder that accepts the request as the last argument. This works like the responder() decorator but the function is passed the request object as the last argument and the request object will be closed automatically:
As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing.
f (Callable[[Request], WSGIApplication]) – the WSGI callable to decorate
a new WSGI callable
WSGIApplication


Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it.
New in version 0.9.
None


The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field.
New in version 0.9.


The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.)
New in version 0.9.


The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET.


The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822.
Changed in version 2.0: The datetime object is timezone-aware.


Disable the data property to avoid reading from the input stream.
Deprecated since version 2.0: Will be removed in Werkzeug 2.1. Create the request with shallow=True instead.
New in version 0.9.


The WSGI environment containing HTTP headers and information from the WSGI server.


Create a new request object based on the values provided. If environ is given missing values are filled from there. This method is useful for small scripts when you need to simulate a request from an URL. Do not use this method for unittesting, there is a full featured client object (Client) that allows to create multipart requests, support for cookies etc.
This accepts the same options as the EnvironBuilder.
Changed in version 0.5: This method now accepts the same arguments as EnvironBuilder. Because of this the environ parameter is now called environ_overrides.
request object
werkzeug.wrappers.request.Request


This reads the buffered incoming data from the client into one bytes object. By default this is cached but that behavior can be changed by setting cache to False.
Usually it’s a bad idea to call this method without checking the content length first as a client could send dozens of megabytes or more to cause memory problems on the server.
Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set parse_form_data to True. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory.
If as_text is set to True the return value will be a decoded string.
New in version 0.9.
Union[bytes, str]


Parse data as JSON.
If the mimetype does not indicate JSON (application/json, see is_json()), this returns None.
If parsing fails, on_json_loading_failed() is called and its return value is used as the return value.
Optional[Any]


The WSGI input stream.
In general it’s a bad idea to use this one because you can easily read past the boundary. Use the stream instead.


boolean that is True if the application is served by a WSGI server that spawns multiple processes.


boolean that is True if the application is served by a multithreaded WSGI server.


boolean that is True if the application will be executed only once in a process lifetime. This is the case for CGI for example, but it’s not guaranteed that the execution only happens one time.


A module or other object that has dumps and loads functions that match the API of the built-in json module.


Creates the form data parser. Instantiates the form_data_parser_class with some parameters.
New in version 0.8.
werkzeug.formparser.FormDataParser


the maximum content length. This is forwarded to the form data parsing function (parse_form_data()). When set and the form or files attribute is accessed and the parsing fails because more than the specified value is transmitted a RequestEntityTooLarge exception is raised.
Have a look at Dealing with Request Data for more details.
New in version 0.5.


the maximum form field size. This is forwarded to the form data parsing function (parse_form_data()). When set and the form or files attribute is accessed and the data in memory for post data is longer than the specified value a RequestEntityTooLarge exception is raised.
Have a look at Dealing with Request Data for more details.
New in version 0.5.


The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server.


The method the request was made with, such as GET.


Called if get_json() parsing fails and isn’t silenced. If this method returns a value, it is used as the return value for get_json(). The default implementation raises BadRequest.
e (ValueError) –
Any


The host that the request originated from. Set access_control_allow_origin on the response to indicate which origins are allowed.


The path part of the URL after root_path. This is the path used for routing within the application.


The part of the URL after the “?”. This is the raw value, use args for the parsed values.