Toggle navigation

Data Structures

Werkzeug provides some subclasses of common Python objects to extend them with additional features. Some of them are used to make them immutable, others are used to change some semantics to better work with HTTP.

General Purpose

Changed in version 0.6: The general purpose classes are now pickleable in each protocol as long as the contained objects are pickleable. This means that the FileMultiDict won’t be pickleable as soon as it contains a file.

class werkzeug.datastructures.TypeConversionDict

Works like a regular dict but the get() method can perform type conversions. MultiDict and CombinedMultiDict are subclasses of this class and provide the same feature.

New in version 0.5.

get(key, default=None, type=None)

Return the default value if the requested data doesn’t exist. If [UNKNOWN NODE title_reference] 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:

[UNKNOWN NODE doctest_block]
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 [UNKNOWN NODE title_reference] 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.
class werkzeug.datastructures.ImmutableTypeConversionDict

Works like a TypeConversionDict but does not support modifications.

New in version 0.5.

copy()

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

class werkzeug.datastructures.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 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 [UNKNOWN NODE title_reference] methods as explained below.

Basic Usage:

[UNKNOWN NODE doctest_block]

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 [UNKNOWN NODE title_reference] 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.

Parameters
mapping – the initial value for the MultiDict. Either a regular dict, an iterable of (key, value) tuples or [UNKNOWN NODE title_reference].
add(key, value)

Adds a new value for the key.

New in version 0.6.

Parameters
  • key – the key for the value.
  • value – the value to add.
clear() → None. Remove all items from D.
copy()

Return a shallow copy of this object.

deepcopy(memo=None)

Return a deep copy of this object.

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 [UNKNOWN NODE title_reference] 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:

[UNKNOWN NODE doctest_block]
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 [UNKNOWN NODE title_reference] 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 [UNKNOWN NODE title_reference], the return value will be an empty list. Just as [UNKNOWN NODE title_reference] [UNKNOWN NODE title_reference] accepts a [UNKNOWN NODE title_reference] 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(k) → True if D has a key k, else False
items(*a, **kw)

Like iteritems(), but returns a list.

iteritems(multi=False)

Return an iterator of (key, value) pairs.

Parameters
multi – If set to [UNKNOWN NODE title_reference] 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.
iterlists()

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

iterlistvalues()

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

[UNKNOWN NODE doctest_block]
itervalues()

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

keys(*a, **kw)

Like iterkeys(), but returns a list.

lists(*a, **kw)

Like iterlists(), but returns a list.

listvalues(*a, **kw)

Like iterlistvalues(), but 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:

[UNKNOWN NODE doctest_block]
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 [UNKNOWN NODE title_reference] and sets that value for [UNKNOWN NODE title_reference].

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 [UNKNOWN NODE title_reference].
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.

[UNKNOWN NODE doctest_block]
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=None)

Like [UNKNOWN NODE title_reference] 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:

[UNKNOWN NODE doctest_block]
Parameters
  • key – The key to be looked up.
  • default_list – An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned.
Returns
to_dict(flat=True)

Return the contents as regular dict. If [UNKNOWN NODE title_reference] is [UNKNOWN NODE title_reference] the returned dict will only have the first item present, if [UNKNOWN NODE title_reference] is [UNKNOWN NODE title_reference] all values will be returned as lists.

Parameters
flat – If set to [UNKNOWN NODE title_reference] the dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key.
Returns
update(other_dict)

update() extends rather than replaces existing key lists:

[UNKNOWN NODE doctest_block]

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:

[UNKNOWN NODE doctest_block]
values(*a, **kw)

Like itervalues(), but returns a list.

viewitems(*a, **kw)

“”“[UNKNOWN NODE title_reference] object providing a view on items”“”

viewkeys(*a, **kw)

“”“[UNKNOWN NODE title_reference] object providing a view on keys”“”

viewlists(*a, **kw)

“”“[UNKNOWN NODE title_reference] object providing a view on lists”“”

viewlistvalues(*a, **kw)

“”“[UNKNOWN NODE title_reference] object providing a view on listvalues”“”

viewvalues(*a, **kw)

“”“[UNKNOWN NODE title_reference] object providing a view on values”“”

class werkzeug.datastructures.OrderedMultiDict(mapping=None)

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.

class werkzeug.datastructures.ImmutableMultiDict(mapping=None)

An immutable MultiDict.

New in version 0.5.

copy()

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

class werkzeug.datastructures.ImmutableOrderedMultiDict(mapping=None)

An immutable OrderedMultiDict.

New in version 0.6.

copy()

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

class werkzeug.datastructures.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:

[UNKNOWN NODE doctest_block]

This works for all read operations and will raise a [UNKNOWN NODE title_reference] for methods that usually change data which isn’t possible.

From Werkzeug 0.3 onwards, the [UNKNOWN NODE title_reference] 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.

class werkzeug.datastructures.ImmutableDict

An immutable dict.

New in version 0.5.

copy()

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

class werkzeug.datastructures.ImmutableList

An immutable list.

New in version 0.5.

Private
class werkzeug.datastructures.FileMultiDict(mapping=None)

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.

add_file(name, file, filename=None, content_type=None)

Adds a new file to the dict. [UNKNOWN NODE title_reference] can be a file name or a file-like or a FileStorage object.

Parameters
  • name – the name of the field.
  • file – a filename or file-like object
  • filename – an optional filename
  • content_type – an optional content type

Others

class werkzeug.datastructures.FileStorage(stream=None, filename=None, name=None, content_type=None, content_length=None, headers=None)

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.

headers

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

Close the underlying file if possible.

content_length

The content-length sent in the header. Usually not available

content_type

The content-type sent in the header. Usually not available

mimetype

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.

mimetype_params

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

For secure file saving also have a look at secure_filename().

Parameters
  • dst – a filename or open file object the uploaded file is saved to.
  • buffer_size – the size of the buffer. This works the same as the [UNKNOWN NODE title_reference] parameter of shutil.copyfileobj().