Werkzeug

Utilities

You can import all these objects directly from werkzeug.

Data Structures

class werkzeug.MultiDict(mapping=None)

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

>>> d = MultiDict([('a', 'b'), ('a', 'c')])
>>> d
MultiDict([('a', 'b'), ('a', 'c')])
>>> d['a']
'b'
>>> d.getlist('a')
['b', 'c']
>>> 'a' in d
True

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 catched in a catch-all for HTTP exceptions.

A MultiDict can be constructed from an iterable of (key, value) tuples, a dict, a MultiDict or with Werkzeug 0.2 onwards some keyword parameters.

Parameter:mapping – the initial value for the MultiDict. Either a regular dict, an iterable of (key, value) tuples or None.
clear()
D.clear() -> None. Remove all items from D.
copy()
Return a shallow copy of this object.
static fromkeys()
dict.fromkeys(S[,v]) -> New dict with keys from S and values equal to v. v defaults to None.
get(key, default=None, type=None)

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:

>>> d = MultiDict(dict(foo='42', bar='blub'))
>>> d.get('foo', type=int)
42
>>> d.get('bar', -1, type=int)
-1
Parameters:
  • key – The key to be looked up.
  • default – The default value to be returned if the key can’t be looked up. If not further specified None is returned.
  • type – A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the default value is returned.
getlist(key, type=None)

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 as get getlist accepts a type parameter. All items will be converted with the callable defined there.

Parameters:
  • key – The key to be looked up.
  • type – A callable that is used to cast the value in the MultiDict. If a ValueError is raised by this callable the value will be removed from the list.
Returns:

a list of all the values for the key.

has_key()
D.has_key(k) -> True if D has a key k, else False
items()

Return a list of (key, value) pairs, where value is the first item in the list associated with the key.

Returns:a list
iteritems()
Like items() but returns an iterator.
iterkeys()
D.iterkeys() -> an iterator over the keys of D
iterlists()

Return a list of all values assoiciated with a key.

Returns:a list
iterlistvalues()
like listvalues() but returns an iterator.
itervalues()
Like values() but returns an iterator.
keys()
D.keys() -> list of D’s keys
lists()

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

Returns:a list
listvalues()

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

>>> d = MultiDict({"foo": [1, 2, 3]})
>>> zip(d.keys(), d.listvalues()) == d.lists()
True
Returns:a list
pop(key, default=no value)

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

>>> d = MultiDict({"foo": [1, 2, 3]})
>>> d.pop("foo")
1
>>> "foo" in d
False
Parameters:
  • key – the key to pop.
  • default – if provided the value to return if the key was not in the dictionary.
popitem()
Pop an item from the dict.
popitemlist()
Pop a (key, list) tuple from the dict.
poplist(key)

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.

setdefault(key, default=None)

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

Parameters:
  • key – The key to be looked up.
  • default – The default value to be returned if the key is not in the dict. If not further specified it’s None.
setlist(key, new_list)

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.

>>> d = MultiDict()
>>> d.setlist('foo', ['1', '2'])
>>> d['foo']
'1'
>>> d.getlist('foo')
['1', '2']
Parameters:
  • key – The key for which the values are set.
  • new_list – An iterable with the new values for the key. Old values are removed first.
setlistdefault(key, default_list=())

Like setdefault but sets multiple values.

Parameters:
  • key – The key to be looked up.
  • default – An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned.
Returns:

a list

to_dict(flat=True)

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.

Parameter:flat – If set to False the dict returned will have lists with all the values in it. Otherwise it will only contain the first item for each key.
Returns:a dict
update(other_dict)
update() extends rather than replaces existing key lists.
values()

Returns a list of the last value on every key list.

Returns:a list.
class werkzeug.CombinedMultiDict(dicts=None)

A read only MultiDict that you can pass multiple MultiDict instances as sequence and it will combine the return values of all wrapped dicts:

>>> from werkzeug import MultiDict, CombinedMultiDict
>>> post = MultiDict([('foo', 'bar')])
>>> get = MultiDict([('blub', 'blah')])
>>> combined = CombinedMultiDict([get, post])
>>> combined['foo']
'bar'
>>> combined['blub']
'blah'

This works for all read operations and will raise a TypeError for methods that usually change data which isn’t possible.

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 catched in a catch-all for HTTP exceptions.

class werkzeug.FileStorage(stream=None, filename=None, name=None, content_type='application/octet-stream', content_length=-1)

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().

stream
The input stream for the uploaded file. This usually points to an open temporary file.
filename
The filename of the file on the client.
name
The name of the form field.
content_type
The content type (mimetype) of the file.
content_length
The length of the file in bytes.
save(dst, buffer_size=16384)

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 the memory during the copy process. It defaults to 16KB.

Parameters:
  • dst – a filename or open file object the uploaded file is saved in.
  • buffer_size – the size of the buffer. This works the same as the length parameter of shutil.copyfileobj().
class werkzeug.Headers([defaults])

An object that stores some headers. It has a dict like interface but is ordered and can store keys multiple times.

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 catched 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. To create a Headers object that uses as internal storage the list or list-like object you can use the linked() class method.

Parameter:defaults – The list of default values for the Headers.
add(_key, _value, **kw)

Add a new header tuple to the list.

Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes:

>>> d = Headers()
>>> d.add('Content-Type', 'text/plain')
>>> d.add('Content-Disposition', 'attachment', filename='foo.png')

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_header(_key, _value, **_kw)

Add a new header tuple to the list.

An alias for add() for compatibility with the wsgiref add_header() method.

clear()
Clears all headers.
extend(iterable)
Extend the headers with a dict or an iterable yielding keys and values.
get(key, default=None, type=None)

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:

>>> d = Headers([('Content-Length', '42')])
>>> d.get('Content-Length', type=int)
42

If a headers object is bound you must notadd unicode strings because no encoding takes place.

Parameters:
  • key – The key to be looked up.
  • default – The default value to be returned if the key can’t be looked up. If not further specified None is returned.
  • type – A callable that is used to cast the value in the Headers. If a ValueError is raised by this callable the default value is returned.
get_all(name)

Return a list of all the values for the named field.

This method is compatible with the wsgiref get_all() method.

getlist(key, type=None)

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 as get() getlist() accepts a type parameter. All items will be converted with the callable defined there.

Parameters:
  • key – The key to be looked up.
  • type – A callable that is used to cast the value in the Headers. If a ValueError is raised by this callable the value will be removed from the list.
Returns:

a list of all the values for the key.

has_key(key)
Check if a key is present.
classmethod linked(headerlist)

Create a new Headers object that uses the list of headers passed as internal storage:

>>> headerlist = [('Content-Length', '40')]
>>> headers = Headers.linked(headerlist)
>>> headers.add('Content-Type', 'text/html')
>>> headerlist
[('Content-Length', '40'), ('Content-Type', 'text/html')]
Parameter:headerlist – The list of headers the class is linked to.
Returns:new linked Headers object.
pop(key=None, default=no value)

Removes and returns a key or index.

Parameter: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.
Returns:an item.
popitem()
Removes a key or index and returns a (key, value) item.
remove(key)

Remove a key.

Parameter:key – The key to be removed.
set(key, value)

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.

Parameters:
  • key – The key to be inserted.
  • value – The value to be inserted.
setdefault(key, value)

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

Parameters:
  • key – The key to be looked up.
  • default – The default value to be returned if the key is not in the dict. If not further specified it’s None.
to_list(charset='utf-8')

Convert the headers into a list and converts the unicode header items to the specified charset.

Returns:list
class werkzeug.EnvironHeaders(environ)

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 catched in a catch-all for HTTP exceptions.

class werkzeug.Accept(values=())

An Accept object is just a list subclass for lists of (value, quality) tuples. It is automatically sorted by quality.

best
The best match as value.
find(key)

Get the position of an entry or return -1.

Parameter:key – The key to be looked up.
index(key)

Get the position of en entry or raise IndexError.

Parameter:key – The key to be looked up.
itervalues()
Iterate over all values.
values()
Return a list of the values, not the qualities.
class werkzeug.MIMEAccept(values=())

Like Accept but with special methods and behavior for mimetypes.

accept_html
True if this object accepts HTML.
accept_xhtml
True if this object accepts XHTML.
class werkzeug.CharsetAccept(values=())
Like Accept but with normalization for charsets.
class werkzeug.CacheControl(values=(), on_update=None)

Subclass of a dict that stores values for a Cache-Control header. It has accesors for all the cache-control directives specified in RFC 2616. The class does not differentiate between request and response directives.

Because the cache-control directives in the HTTP header use dashes the python descriptors use underscores for that.

To get a header of the CacheControl object again you can convert the object into a string or call the to_header() method. If you plan to subclass it and add your own items have a look at the sourcecode for that class.

The following attributes are exposed:

no_cache, no_store, max_age, max_stale, min_fresh, no_transform, only_if_cached, public, private, must_revalidate, proxy_revalidate, and s_maxage

Changed in version 0.4.

static cache_property(key, empty, type)
Return a new property object for a cache header. Useful if you want to add support for a cache extension in a subclass.
max_age
accessor for ‘max-age’
max_stale
accessor for ‘max-stale’
min_fresh
accessor for ‘min-fresh’
must_revalidate
accessor for ‘must-revalidate’
no_cache
accessor for ‘no-cache’
no_store
accessor for ‘no-store’
no_transform
accessor for ‘no-transform’
only_if_cached
accessor for ‘only-if-cached’
private
accessor for ‘private’
proxy_revalidate
accessor for ‘proxy-revalidate’
public
accessor for ‘public’
s_maxage
accessor for ‘s-maxage’
to_header()
Convert the stored values into a cache control header.
class werkzeug.HeaderSet(headers=None, on_update=None)

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 instanciation works like this:

>>> hs = HeaderSet(['foo', 'bar', 'baz'])
>>> hs
HeaderSet(['foo', 'bar', 'baz'])
add(header)
Add a new header to the set.
as_set(preserve_casing=False)

Return the set as real python set structure. When calling this all the items are converted to lowercase and the ordering is lost.

Parameter: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()
Clear the set.
discard(header)

Like remove() but ignores errors.

Parameter:header – the header to be discarded.
find(header)

Return the index of the header in the set or return -1 if not found.

Parameter:header – the header to be looked up.
index(header)

Return the index of the headerin the set or raise an IndexError.

Parameter:header – the header to be looked up.
remove(header)

Remove a layer from the set. This raises an KeyError if the header is not in the set.

Changed in version 0.5: In older version a IndexError was raised instead of an KeyError if the object was missing.

Parameter:header – the header to be removed.
to_header()
Convert the header set into an HTTP header string.
update(iterable)

Add all the headers from the iterable to the set.

Parameter:iterable – updates the set with the items from the iterable.
class werkzeug.UserAgent(environ_or_string)

Represents a user agent. Pass it a WSGI environment or an user agent string and you can inspect some of the details from the user agent string via the attributes. The following attribute exist:

  • string, the raw user agent string
  • platform, the browser platform
  • browser, the name of the browser
  • version, the version of the browser
  • language, the language of the browser
class werkzeug.ETags(strong_etags=None, weak_etags=None, star_tag=False)

A set that can be used to check if one etag is present in a collection of etags.

as_set(include_weak=False)
Convert the ETags object into a python set. Per default all the weak etags are not part of this set.
contains(etag)
Check if an etag is part of the set ignoring weak tags.
contains_raw(etag)
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 weak only.
contains_weak(etag)
Check if an etag is part of the set including weak and strong tags.
is_weak(etag)
Check if an etag is weak.
to_header()
Convert the etags set into a HTTP header string.
class werkzeug.Authorization(auth_type, data=None)

Represents an Authorization header sent by the client. You should not create this kind of object yourself but use it when it’s returned by the parse_authorization_header function.

This object is a dict subclass and can be altered by setting dict items but it should be considered immutable as it’s returned by the client and not meant for modifications.

cnonce
If the server sent a qop-header in the WWW-Authenticate header, the client has to provide this value for HTTP digest auth. See the RFC for more details.
nc
The nonce count value transmitted by clients if a qop-header is also transmitted. HTTP digest auth only.
nonce
The nonce the server send for digest auth, send back by the client. A nonce should be unique for every 401 response for HTTP digest auth.
opaque
The opaque header from the server returned unchanged by the client. It is recommended that this string be base64 or hexadecimal data. Digest auth only.
password
When the authentication type is basic this is the password transmitted by the client, else None.
qop
Indicates what “quality of protection” the client has applied to the message for HTTP digest auth.
realm
This is the server realm send back for digest auth. For HTTP digest auth.
response
A string of 32 hex digits computed as defined in RFC 2617, which proves that the user knows a password. Digest auth only.
uri
The URI from Request-URI of the Request-Line; duplicated because proxies are allowed to change the Request-Line in transit. HTTP digest auth only.
username
The username transmitted. This is set for both basic and digest auth all the time.
class werkzeug.WWWAuthenticate(auth_type=None, values=None, on_update=None)

Provides simple access to WWW-Authenticate headers.

algorithm
A string indicating a pair of algorithms used to produce the digest and a checksum. If this is not present it is assumed to be “MD5”. If the algorithm is not understood, the challenge should be ignored (and a different one used, if there is more than one).
static auth_property(name, doc=None)

A static helper function for subclasses to add extra authentication system properites onto a class:

class FooAuthenticate(WWWAuthenticate):
    special_realm = auth_property('special_realm')

For more information have a look at the sourcecode to see how the regular properties (realm etc. are implemented).

domain
A list of URIs that define the protection space. If a URI is an absolte path, it is relative to the canonical root URL of the server being accessed.
nonce
A server-specified data string which should be uniquely generated each time a 401 response is made. It is recommended that this string be base64 or hexadecimal data.
opaque
A string of data, specified by the server, which should be returned by the client unchanged in the Authorization header of subsequent requests with URIs in the same protection space. It is recommended that this string be base64 or hexadecimal data.
qop
A set of quality-of-privacy modifies such as auth and auth-int.
realm
A string to be displayed to users so they know which username and password to use. This string should contain at least the name of the host performing the authentication and might additionally indicate the collection of users who might have access.
set_basic(realm='authentication required')
Clear the auth info and enable basic auth.
set_digest(realm, nonce, qop=('auth', ), opaque=None, algorithm=None, stale=False)
Clear the auth info and enable digest auth.
stale
A flag, indicating that the previous request from the client was rejected because the nonce value was stale.
to_header()
Convert the stored values into a WWW-Authenticate header.
type
The type of the auth machanism. HTTP currently specifies Basic and Digest.

Middlewares

class werkzeug.SharedDataMiddleware(app, exports, disallow=None, cache=True)

A WSGI middleware that provides static content for development environments or simple server setups. Usage is quite simple:

import os
from werkzeug import SharedDataMiddleware

app = SharedDataMiddleware(app, {
    '/shared': os.path.join(os.path.dirname(__file__), 'shared')
})

The contents of the folder ./shared will now be available on http://example.com/shared/. This is pretty useful during development because a standalone media server is not required. One can also mount files on the root folder and still continue to use the application because the shared data middleware forwards all unhandled requests to the application, even if the requests are below one of the shared folders.

If pkg_resources is available you can also tell the middleware to serve files from package data:

app = SharedDataMiddleware(app, {
    '/shared': ('myapplication', 'shared_files')
})

This will then serve the shared_files folder in the myapplication Python package.

The optional disallow parameter can be a list of fnmatch rules for files that are not accessible from the web. If cache is set to False no caching headers are sent.

is_allowed(filename)
Subclasses can override this method to disallow the access to certain files. However by providing disallow in the constructor this method is overwritten.
class werkzeug.DispatcherMiddleware(app, mounts=None)

Allows one to mount middlewares or application in a WSGI application. This is useful if you want to combine multiple WSGI applications:

app = DispatcherMiddleware(app, {
    '/app2':        app2,
    '/app3':        app3
})

WSGI Helpers

class werkzeug.ClosingIterator(iterable, callbacks=None)

The WSGI specification requires that all middlewares and gateways respect the close callback of an iterator. Because it is useful to add another close action to a returned iterator and adding a custom iterator is a boring task this class can be used for that:

return ClosingIterator(app(environ, start_response), [cleanup_session,
                                                      cleanup_locals])

If there is just one close function it can be bassed instead of the list.

A closing iterator is non needed if the application uses response objects and finishes the processing if the resonse is started:

try:
    return response(environ, start_response)
finally:
    cleanup_session()
    cleanup_locals()
class werkzeug.FileWrapper(file, buffer_size=8192)

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.

Parameters:
  • file – a file-like object with a read() method.
  • buffer_size – number of bytes for one iteration.
class werkzeug.LimitedStream(stream, limit, silent=False)

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 raises a BadRequest. 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.

The silent parameter has no effect if is_exhausted() is overriden by a subclass.

Parameters:
  • stream – the stream to wrap.
  • limit – the limit for the stream, must not be longer than what the string can provide if the stream does not end with EOF (like wsgi.input)
  • silent – If set to True the stream will allow reading past the limit and will return an empty string.
exhaust(chunk_size=16384)

Exhaust the stream. This consumes all the data left until the limit is reached.

Parameter:chunk_size – the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results.
is_exhausted
If the stream is exhausted this attribute is True.
on_exhausted()

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

Per default this raises a BadRequest.

read(size=None)

Read size bytes or if size is not provided everything is read.

Parameter:size – the number of bytes read.
readline(size=None)
Read a line from the stream. Arguments are forwarded to the readline function of the underlaying stream if it supports them.
readlines(size=None)
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 underlaying stream supports it for readline.
werkzeug.get_host(environ)

Return the real host for the given WSGI environment. This takes care of the X-Forwarded-Host header.

Parameter:environ – the WSGI environment to get the host of.
werkzeug.get_current_url(environ, root_only=False, strip_querystring=False, host_only=False)

A handy helper function that recreates the full URL for the current request or parts of it. Here an example:

>>> env = create_environ("/?param=foo", "http://localhost/script")
>>> get_current_url(env)
'http://localhost/script/?param=foo'
>>> get_current_url(env, root_only=True)
'http://localhost/script/'
>>> get_current_url(env, host_only=True)
'http://localhost/'
>>> get_current_url(env, strip_querystring=True)
'http://localhost/script/'
Parameters:
  • environ – the WSGI environment to get the current URL of.
  • root_only – set True if you only want the root URL.
  • strip_querystring – set to True if you don’t want the querystring.
  • host_only – set to True if the host URL should be returned.
werkzeug.responder(f)

Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application.

Example:

@responder
def application(environ, start_response):
    return Response('Hello World!')
werkzeug.create_environ(path='/', base_url=None, query_string=None, method='GET', input_stream=None, content_type=None, content_length=0, errors_stream=None, multithread=False, multiprocess=False, run_once=False)

Create a new WSGI environ dict based on the values passed. The first parameter should be the path of the request which defaults to ‘/’. The second one can either be a absolute path (in that case the host is localhost:80) or a full path to the request with scheme, netloc port and the path to the script.

If the path contains a query string it will be used, even if the query_string parameter was given. If it does not contain one the query_string parameter is used as querystring. In that case it can either be a dict, MultiDict or string.

The following options exist:

Parameters:
  • path – the path of the request. See explanation above.
  • method – the request method.
  • input_stream – the input stream. Defaults to an empty read only stream.
  • content_type – the content type for this request.
  • content_length – the value for the content length header.
  • errors_stream – the wsgi.errors stream. Defaults to sys.stderr.
  • multithread – the multithreaded flag for the WSGI environment.
  • multiprocess – the multiprocess flag for the WSGI environment.
  • run_once – the run_once flag for the WSGI environment.
werkzeug.run_wsgi_app(app, environ, buffered=False)

Return a tuple in the form (app_iter, status, headers) of the application output. This works best if you pass it an application that returns a iterator all the time.

Sometimes applications may use the write() callable returned by the start_response function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should set buffered to True which enforces buffering.

If passed an invalid WSGI application the behavior of this function is undefined. Never pass non-conforming WSGI applications to this function.

Parameters:
  • app – the application to execute.
  • buffered – set to True to enforce buffering.
Returns:
werkzeug.test_app(environ, start_response)
Simple test application that dumps the environment.
werkzeug.wrap_file(environ, file, buffer_size=8192)

Wraps a file. This uses the WSGI server’s file wrapper if available or otherwise the generic FileWrapper.

New in version 0.5.

If the file wrapper from the WSGI server is used it’s important to not iterate over it from inside the application but to pass it through unchanged. If you want to pass out a file wrapper inside a response object you have to set direct_passthrough to True.

More information about file wrappers are available in PEP 333.

Parameters:
  • file – a file-like object with a read() method.
  • buffer_size – number of bytes for one iteration.
werkzeug.pop_path_info(environ)

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 there are empty segments ('/foo//bar) these are ignored but properly pushed to the SCRIPT_NAME:

>>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
>>> pop_path_info(env)
'a'
>>> env['SCRIPT_NAME']
'/foo/a'
>>> pop_path_info(env)
'b'
>>> env['SCRIPT_NAME']
'/foo/a/b'

New in version 0.5.

Parameter:environ – the WSGI environment that is modified.
werkzeug.peek_path_info(environ)

Returns the next segment on the PATH_INFO or None if there is none. Works like pop_path_info() without modifying the environment:

>>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'}
>>> peek_path_info(env)
'a'
>>> peek_path_info(env)
'a'

New in version 0.5.

Parameter:environ – the WSGI environment that is checked.
werkzeug._easteregg(app)
Like the name says. But who knows how it works?

URL Helpers

class werkzeug.Href(base='./', charset='utf-8', sort=False, key=None)

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:

>>> href = Href('/foo')
>>> href('bar', 23)
'/foo/bar/23'
>>> href('foo', bar=23)
'/foo/foo?bar=23'

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:

>>> href(is_=42)
'/foo?is=42'
>>> href({'foo': 'bar'})
'/foo?foo=bar'

Combining of both methods is not allowed:

>>> href({'foo': 'bar'}, bar=42)
Traceback (most recent call last):
  ...
TypeError: keyword arguments and query-dicts can't be combined

Accessing attributes on the href object creates a new href object with the attribute name as prefix:

>>> bar_href = href.bar
>>> bar_href("blub")
'/foo/bar/blub'

If sort is set to True the items are sorted by key or the default sorting algorithm:

>>> href = Href("/", sort=True)
>>> href(a=1, b=2, c=3)
'/?a=1&b=2&c=3'

New in version 0.5: sort and key were added.

werkzeug.url_decode(s, charset='utf-8', decode_keys=False, include_empty=True, errors='ignore', separator='&')

Parse a querystring and return it as MultiDict. Per default only values are decoded into unicode strings. If decode_keys is set to True the same will happen for keys.

Per default a missing value for a key will default to an empty key. If you don’t want that behavior you can set include_empty to False.

Per default encoding errors are ignore. If you want a different behavior you can set errors to 'replace' or 'strict'. In strict mode a HTTPUnicodeError is raised.

Changed in version 0.5: In previous versions “;” and “&” could be used for url decoding. This changed in 0.5 where only “&” is supported. If you want to use “;” instead a different separator can be provided.

Parameters:
  • s – a string with the query string to decode.
  • charset – the charset of the query string.
  • decode_keys – set to True if you want the keys to be decoded as well.
  • include_empty – Set to False if you don’t want empty values to appear in the dict.
  • separator – the pair separator to be used, defaults to &
  • errors – the decoding error behavior.
werkzeug.url_encode(obj, charset='utf-8', encode_keys=False, sort=False, key=None, separator='&')

URL encode a dict/MultiDict. If a value is None it will not appear in the result string. Per default only values are encoded into the target charset strings. If encode_keys is set to True unicode keys are supported too.

If sort is set to True the items are sorted by key or the default sorting algorithm.

New in version 0.5: sort, key, and separator were added.

Parameters:
  • obj – the object to encode into a query string.
  • charset – the charset of the query string.
  • encode_keys – set to True if you have unicode keys.
  • sort – set to True if you want parameters to be sorted by key.
  • separator – the separator to be used for the pairs.
  • key – an optional function to be used for sorting. For more details check out the sorted() documentation.
werkzeug.url_quote(s, charset='utf-8', safe='/:')

URL encode a single string with a given encoding.

Parameters:
  • s – the string to quote.
  • charset – the charset to be used.
  • safe – an optional sequence of safe characters.
werkzeug.url_quote_plus(s, charset='utf-8', safe='')

URL encode a single string with the given encoding and convert whitespace to “+”.

Parameters:
  • s – the string to quote.
  • charset – the charset to be used.
  • safe – an optional sequence of safe characters.
werkzeug.url_unquote(s, charset='utf-8', errors='ignore')

URL decode a single string with a given decoding.

Per default encoding errors are ignore. If you want a different behavior you can set errors to 'replace' or 'strict'. In strict mode a HTTPUnicodeError is raised.

Parameters:
  • s – the string to unquote.
  • charset – the charset to be used.
  • errors – the error handling for the charset decoding.
werkzeug.url_unquote_plus(s, charset='utf-8', errors='ignore')

URL decode a single string with the given decoding and decode a “+” to whitespace.

Per default encoding errors are ignore. If you want a different behavior you can set errors to 'replace' or 'strict'. In strict mode a HTTPUnicodeError is raised.

Parameters:
  • s – the string to unquote.
  • charset – the charset to be used.
  • errors – the error handling for the charset decoding.
werkzeug.url_fix(s, charset='utf-8')

Sometimes you get an URL by a user that just isn’t a real URL because it contains unsafe characters like ‘ ‘ and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user:

>>> url_fix(u'http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)')
'http://de.wikipedia.org/wiki/Elf%20%28Begriffskl%C3%A4rung%29'
Parameters:
  • s – the string with the URL to fix.
  • charset – The target charset for the URL if the url was given as unicode string.

HTML Helpers

class werkzeug.HTMLBuilder(dialect)

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:

>>> html.p(class_='foo', *[html.a('foo', href='foo.html'), ' ',
...                        html.a('bar', href='bar.html')])
u'<p class="foo"><a href="foo.html">foo</a> <a href="bar.html">bar</a></p>'

This class works around some browser limitations and can not be used for arbitrary SGML/XML generation. For that purpose lxml and similar libraries exist.

Calling the builder escapes the string passed:

>>> html.p(html("<foo>"))
u'<p>&lt;foo&gt;</p>'
werkzeug.escape(s, quote=False)

Replace special characters “&”, “<” and “>” to HTML-safe sequences. If the optional flag quote is True, the quotation mark character (“) is also translated.

There is a special handling for None which escapes to an empty string.

Parameters:
  • s – the string to escape.
  • quote – set to true to also escape double quotes.
werkzeug.unescape(s)

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

Parameter:s – the string to unescape.

HTTP Helpers

werkzeug.dump_header(iterable, allow_token=True)

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.

Parameters:
  • iterable – the iterable or dict of values to quote.
  • allow_token – if set to False tokens as values are sallowed. See quote_header_value() for more details.
werkzeug.cookie_date(expires=None)

Formats the time to ensure compatibility with Netscape’s cookie standard.

Accepts a floating point number expressed in seconds since the epoc in, a datetime object or a timetuple. All times in UTC. The parse_date() function can be used to parse such a date.

Outputs a string in the format Wdy, DD-Mon-YYYY HH:MM:SS GMT.

Parameter:expires – If provided that date is used, otherwise the current.
werkzeug.http_date(timestamp=None)

Formats the time to match the RFC1123 date format.

Accepts a floating point number expressed in seconds since the epoc in, a datetime object or a timetuple. All times in UTC. The parse_date() function can be used to parse such a date.

Outputs a string in the format Wdy, DD Mon YYYY HH:MM:SS GMT.

Parameter:timestamp – If provided that date is used, otherwise the current.
werkzeug.parse_form_data(environ, stream_factory=None, charset='utf-8', errors='ignore')

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 or PUT.

If the mimetype of the data transmitted is multipart/form-data the files multidict will be filled with FileStorage objects. If the mimetype is unknow the input stream is wrapped and returned as first argument, else the stream is empty.

This function does not raise exception, even if the input data is malformed.

Parameters:
  • environ – the WSGI environment to be used for parsing.
  • stream_factory – An optional callable that returns a new read and writeable file descriptor. This callable works the same as _get_file_stream().
  • charset – The character set for URL and url encoded form data.
  • errors – The encoding error behavior.
Returns:

A tuple in the form (stream, form, files).

werkzeug.parse_etags(value)

Parse an etag header.

Parameter:value – the tag header to parse
Returns:an ETags object.
werkzeug.quote_etag(etag, weak=False)

Quote an etag.

Parameters:
  • etag – the etag to quote.
  • weak – set to True to tag it “weak”.
werkzeug.unquote_etag(etag)

Unquote a single etag:

>>> unquote_etag('w/"bar"')
('bar', True)
>>> unquote_etag('"bar"')
('bar', False)
Parameter:etag – the etag identifier to unquote.
Returns:a (etag, weak) tuple.
werkzeug.generate_etag(data)
Generate an etag for some data.
werkzeug.is_resource_modified(environ, etag=None, data=None, last_modified=None)

Convenience method for conditional requests.

Parameters:
  • environ – the WSGI environment of the request to be checked.
  • etag – the etag for the response for comparision.
  • data – or alternatively the data of the response to automatically generate an etag using generate_etag().
  • last_modified – an optional date of the last modification.
Returns:

True if the resource was modified, otherwise False.

werkzeug.parse_options_header(value)

Parse a Content-Type like header into a tuple with the content type and the options:

>>> parse_options_header('Content-Type: text/html; mimetype=text/html')
('Content-Type: text/html', {'mimetype': 'text/html'})

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.

New in version 0.5.

Parameter:value – the header to parse.
Returns:(str, options)
werkzeug.parse_set_header(value, on_update=None)

Parse a set like header and return a HeaderSet object. The return value is an object that treats the items case insensitive and keeps the order of the items.

Parameters:
  • value – a set header to be parsed.
  • on_update – an optional callable that is called every time a value on the HeaderSet object is changed.
Returns:

a HeaderSet

werkzeug.parse_list_header(value)

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.

Parameter:value – a string with a list header.
Returns:list
werkzeug.parse_dict_header(value)

Parse lists of key, value paits as described by RFC 2068 Section 2 and convert them into a python dict. If there is no value for a key it will be None.

Parameter:value – a string with a dict header.
Returns:dict
werkzeug.parse_accept_header(value[, class])

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 (basicly 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.

Parameters:
  • value – the accept header string to be parsed.
  • cls – the wrapper class for the return value (can be Accept or a subclass thereof)
Returns:

an instance of cls.

werkzeug.parse_cache_control_header(value, on_update=None)

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.

Parameters:
  • value – a cache control header to be parsed.
  • on_update – an optional callable that is called every time a value on the CacheControl object is changed.
Returns:

a CacheControl object.

werkzeug.parse_date(value)

Parse one of the following date formats into a datetime object:

Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
Sun Nov  6 08:49:37 1994       ; ANSI C's asctime() format

If parsing fails the return value is None.

Parameter:value – a string with a supported date format.
Returns:a datetime.datetime object.
werkzeug.parse_authorization_header(value)

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.

Parameter:value – the authorization header to parse.
Returns:a Authorization object or None.
werkzeug.parse_www_authenticate_header(value, on_update=None)

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

Parameters:
  • value – a WWW-Authenticate header to parse.
  • on_update – an optional callable that is called every time a value on the WWWAuthenticate object is changed.
Returns:

a WWWAuthenticate object.

werkzeug.remove_entity_headers(headers)

Remove all entity headers from a list or Headers object. This operation works in-place.

Parameter:headers – a list or Headers object.
werkzeug.remove_hop_by_hop_headers(headers)

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.

Parameter:headers – a list or Headers object.
werkzeug.is_entity_header(header)

Check if a header is an entity header.

New in version 0.5.

Parameter:header – the header to test.
Returns:True if it’s an entity header, False otherwise.
werkzeug.is_hop_by_hop_header(header)

Check if a header is an HTTP/1.1 “Hop-by-Hop” header.

New in version 0.5.

Parameter:header – the header to test.
Returns:True if it’s an entity header, False otherwise.
werkzeug.quote_header_value(value, extra_chars='', allow_token=True)

Quote a header value if necessary.

New in version 0.5.

Parameters:
  • value – the value to quote.
  • extra_chars – a list of extra characters to skip quoting.
  • allow_token – if this is enabled token values are returned unchanged.
werkzeug.unquote_header_value(value)

Unquotes a header value. (Reversal of quote_header_value()). This does not use the real unquoting but what browsers are actually using for quoting.

New in version 0.5.

Parameter:value – the header value to unquote.
werkzeug.HTTP_STATUS_CODES
A dict of status code -> default status message pairs. This is used by the wrappers and other places where a integer status code is expanded to a string throughout Werkzeug.

General Helpers

class werkzeug.cached_property(func, name=None, doc=None, writeable=False)

A decorator that converts a function into a lazy property. The function wrapped is called the first time to retrieve the result and than that calculated result is used the next time you access the value:

class Foo(object):

    @cached_property
    def foo(self):
        # calculate something important here
        return 42

Changed in version 0.5: cached properties are now optionally writeable.

static refresh(object, attributes)

Helper function that invalidates the property cache. This can be useful if you have a function that changes a value that the cached one depends on:

@cached_property
def foo(self):
    return '%s/foo' % self.bar

def change_bar(self):
    self.bar += 1
    cached_property.refresh(self, ['foo'])

New in version 0.5.

Parameters:
  • object – the object with the attributes
  • attributes – an iterable with the attributes to refresh
class werkzeug.environ_property(name, default=None, load_func=None, dump_func=None, read_only=None, doc=None)

Maps request attributes to environment variables. This works not only for the Werzeug request object, but also any other class with an environ attribute:

>>> class Test(object):
...     environ = {'key': 'value'}
...     test = environ_property('key')
>>> var = Test()
>>> var.test
'value'

If you pass it a second value it’s used as default if the key does not exist, the third one can be a converter that takes a value and converts it. If it raises ValueError or TypeError the default value is used. If no default value is provided None is used.

Per default the property is read only. You have to explicitly enable it by passing read_only=False to the constructor.

class werkzeug.header_property(name, default=None, load_func=None, dump_func=None, read_only=None, doc=None)
Like environ_property but for headers.

Parse a cookie. Either from a string or WSGI environ.

Per default encoding errors are ignore. If you want a different behavior you can set errors to 'replace' or 'strict'. In strict mode a HTTPUnicodeError is raised.

Parameters:
  • header – the header to be used to parse the cookie. Alternatively this can be a WSGI environment.
  • charset – the charset for the cookie values.
  • errors – the error behavior for the charset decoding.

Creates a new Set-Cookie header without the Set-Cookie prefix The parameters are the same as in the cookie Morsel object in the Python standard library but it accepts unicode data too.

Parameters:
  • max_age – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session. Additionally timedelta objects are accepted too.
  • expires – should be a datetime object or unix timestamp.
  • path – limits the cookie to a given path, per default it will span the whole domain.
  • domain – Use this if you want to set a cross-domain cookie. For example, domain=".example.com" will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it.
  • secure – The cookie will only be available via HTTPS
  • httponly – disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers.
  • charset – the encoding for unicode values.
  • sync_expires – automatically set expires if max_age is defined but expires not.
werkzeug.redirect(location, code=302)

Return a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, and 307. 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.

Parameters:
  • location – the location the response should redirect to.
  • code – the redirect status code.
werkzeug.append_slash_redirect(environ, code=301)

Redirect to the same URL but with a slash appended. The behavior of this function is undefined if the path ends with a slash already.

Parameters:
  • environ – the WSGI environment for the request that triggers the redirect.
  • code – the status code for the redirect.
werkzeug.import_string(import_name, silent=False)

Imports an object based on a string. This use 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 the silent is True the return value will be None if the import fails.

Parameters:
  • import_name – the dotted name for the object to import.
  • silent – if set to True import errors are ignored and None is returned instead.
Returns:

imported object

werkzeug.find_modules(import_path, include_packages=False, recursive=False)

Find all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application.

Packages are not returned unless include_packages is True. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module.

Parameters:
  • import_name – the dotted name for the package to find child modules.
  • include_packages – set to True if packages should be returned too.
  • recursive – set to True if recursion should happen.
Returns:

generator

werkzeug.validate_arguments(func, args, kwargs, drop_extra=True)

Check if the function accepts the arguments and keyword arguments. Returns a new (args, kwargs) tuple that can savely be passed to the function without causing a TypeError because the function signature is incompatible. If drop_extra is set to True (which is the default) any extra positional or keyword arguments are dropped automatically.

The exception raised provides three attributes:

missing
A set of argument names that the function expected but where missing.
extra
A dict of keyword arguments that the function can not handle but where provided.
extra_positional
A list of values that where given by positional argument but the function cannot accept.

This can be useful for decorators that forward user submitted data to a view function:

from werkzeug import ArgumentValidationError, validate_arguments

def sanitize(f):
    def proxy(request):
        data = request.values.to_dict()
        try:
            args, kwargs = validate_arguments(f, (request,), data)
        except ArgumentValidationError:
            raise BadRequest('The browser failed to transmit all '
                             'the data expected.')
        return f(*args, **kwargs)
    return proxy
Parameters:
  • func – the function the validation is performed against.
  • args – a tuple of positional arguments.
  • kwargs – a dict of keyword arguments.
  • drop_extra – set to False if you don’t want extra arguments to be silently dropped.
Returns:

tuple in the form (args, kwargs).

werkzeug.bind_arguments(func, args, kwargs)

Bind the arguments provided into a dict. When passed a function, a tuple of arguments and a dict of keyword arguments bind_arguments returns a dict of names as the function would see it. This can be useful to implement a cache decorator that uses the function arguments to build the cache key based on the values of the arguments.

Parameters:
  • func – the function the arguments should be bound for.
  • args – tuple of positional arguments.
  • kwargs – a dict of keyword arguments.
Returns:

a dict of bound keyword arguments.