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¶
Changelog
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.MultiDictandCombinedMultiDictare subclasses of this class and provide the same feature.Changelog
Added in version 0.5.
- get(key: K) V | None¶
- get(key: K, default: V) V
- get(key: K, default: T) V | T
- get(key: str, type: Callable[[V], T]) T | None
- get(key: str, default: T, type: Callable[[V], T]) T
Return the default value if the requested data doesn’t exist. If
typeis provided and is a callable it should convert the value, return it or raise aValueErrorif that is not possible. In this case the function will return the default as if the value was not found:>>> d = TypeConversionDict(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
Noneis returned.type – A callable that is used to cast the value in the
MultiDict. If aValueErroror aTypeErroris raised by this callable the default value is returned.
Changelog
Changed in version 3.0.2: Returns the default value on
TypeError, too.
- class werkzeug.datastructures.ImmutableTypeConversionDict¶
Works like a
TypeConversionDictbut does not support modifications.Changelog
Added 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).- Return type:
TypeConversionDict[K, V]
- class werkzeug.datastructures.MultiDict(mapping=None)¶
A
MultiDictis 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.MultiDictimplements 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 thelistmethods 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
KeyErrorraised by this class is also a subclass of theBadRequestHTTP exception and will render a page for a400 BAD REQUESTif caught in a catch-all for HTTP exceptions.A
MultiDictcan be constructed from an iterable of(key, value)tuples, a dict, aMultiDictor from Werkzeug 0.2 onwards some keyword parameters.- Parameters:
mapping (MultiDict[K, V] | cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] | cabc.Iterable[tuple[K, V]] | None) – the initial value for the
MultiDict. Either a regular dict, an iterable of(key, value)tuples orNone.
Changed in version 3.1: Implement
|and|=operators.- add(key, value)¶
Adds a new value for the key.
Changelog
Added in version 0.6.
- Parameters:
key (K) – the key for the value.
value (V) – the value to add.
- Return type:
None
- getlist(key: K) list[V]¶
- getlist(key: K, type: Callable[[V], T]) list[T]
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 likeget,getlistaccepts atypeparameter. All items will be converted with the callable defined there.- Parameters:
key – The key to be looked up.
type – Callable to convert each value. If a
ValueErrororTypeErroris raised, the value is omitted.
- Returns:
a
listof all the values for the key.
Changed in version 3.1: Catches
TypeErrorin addition toValueError.
- 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 (K) – The key for which the values are set.
new_list (Iterable[V]) – An iterable with the new values for the key. Old values are removed first.
- Return type:
None
- setdefault(key: K) None¶
- setdefault(key: K, default: V) V
Returns the value for the key if it is in the dict, otherwise it returns
defaultand sets that value forkey.- 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.
- setlistdefault(key, default_list=None)¶
Like
setdefaultbut 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:>>> d = MultiDict({"foo": 1}) >>> d.setlistdefault("foo").extend([2, 3]) >>> d.getlist("foo") [1, 2, 3]
- Parameters:
key (K) – The key to be looked up.
default_list (Iterable[V] | None) – 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- Return type:
list[V]
- items(multi=False)¶
Return an iterator of
(key, value)pairs.- Parameters:
multi (bool) – If set to
Truethe 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 type:
Iterable[tuple[K, V]]
- lists()¶
Return a iterator of
(key, values)pairs, where values is the list of all values associated with the key.- Return type:
Iterable[tuple[K, list[V]]]
- values()¶
Returns an iterator of the first value on every key’s value list.
- Return type:
Iterable[V]
- listvalues()¶
Return an iterator of all values associated with a key. Zipping
keys()and this is the same as callinglists():>>> d = MultiDict({"foo": [1, 2, 3]}) >>> zip(d.keys(), d.listvalues()) == d.lists() True
- Return type:
Iterable[list[V]]
- copy()¶
Return a shallow copy of this object.
- Return type:
te.Self
- deepcopy(memo=None)¶
Return a deep copy of this object.
- Parameters:
memo (t.Any)
- Return type:
te.Self
- to_dict() dict[K, V]¶
- to_dict(flat: Literal[False]) dict[K, list[V]]
Return the contents as regular dict. If
flatisTruethe returned dict will only have the first item present, ifflatisFalseall values will be returned as lists.- Parameters:
flat – If set to
Falsethe dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key.- Returns:
a
dict
- update(mapping)¶
update() extends rather than replaces existing key lists:
>>> a = MultiDict({'x': 1}) >>> b = MultiDict({'x': 2, 'y': 3}) >>> a.update(b) >>> a MultiDict([('y', 3), ('x', 1), ('x', 2)])
If the value list for a key in
other_dictis empty, no new values will be added to the dict and the key will not be created:>>> x = {'empty_list': []} >>> y = MultiDict() >>> y.update(x) >>> y MultiDict([])
- Parameters:
mapping (MultiDict[K, V] | Mapping[K, V | list[V] | tuple[V, ...] | set[V]] | Iterable[tuple[K, V]])
- Return type:
None
- pop(key: K) V¶
- pop(key: K, default: V) V
- pop(key: K, default: T) V | T
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.
- Return type:
tuple[K, V]
- poplist(key)¶
Pop the list for a key from the dict. If the key is not in the dict an empty list is returned.
Changelog
Changed in version 0.5: If the key does no longer exist a list is returned instead of raising an error.
- Parameters:
key (K)
- Return type:
list[V]
- popitemlist()¶
Pop a
(key, list)tuple from the dict.- Return type:
tuple[K, list[V]]
- clear() None. Remove all items from D.¶
- classmethod fromkeys(iterable, value=None, /)¶
Create a new dictionary with keys from iterable and values set to value.
- get(key, default=None, type=None)¶
Return the default value if the requested data doesn’t exist. If
typeis provided and is a callable it should convert the value, return it or raise aValueErrorif that is not possible. In this case the function will return the default as if the value was not found:>>> d = TypeConversionDict(foo='42', bar='blub') >>> d.get('foo', type=int) 42 >>> d.get('bar', -1, type=int) -1
- Parameters:
key (K) – The key to be looked up.
default (V | T | None) – The default value to be returned if the key can’t be looked up. If not further specified
Noneis returned.type (Callable[[V], T] | None) – A callable that is used to cast the value in the
MultiDict. If aValueErroror aTypeErroris raised by this callable the default value is returned.
- Return type:
V | T | None
Changelog
Changed in version 3.0.2: Returns the default value on
TypeError, too.
- keys() a set-like object providing a view on D's keys¶
- class werkzeug.datastructures.OrderedMultiDict¶
Works like a regular
MultiDictbut preserves the order of the fields. To convert the ordered multi dict into a list you can use theitems()method and pass itmulti=True.In general an
OrderedMultiDictis an order of magnitude slower than aMultiDict.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 theto_dict()method, otherwise the internal bucket objects are exposed.Deprecated since version 3.1: Will be removed in Werkzeug 3.2. Use
MultiDictinstead.
- class werkzeug.datastructures.ImmutableMultiDict¶
An immutable
OrderedMultiDict.Deprecated since version 3.1: Will be removed in Werkzeug 3.2. Use
ImmutableMultiDictinstead.Changelog
Added in version 0.6.
- werkzeug.datastructures.ImmutableOrderedMultiDict¶
alias of
_ImmutableOrderedMultiDict
- class werkzeug.datastructures.CombinedMultiDict(dicts=None)¶
A read only
MultiDictthat you can pass multipleMultiDictinstances as sequence and it will combine the return values of all wrapped dicts:>>> from werkzeug.datastructures import CombinedMultiDict, MultiDict >>> 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
TypeErrorfor methods that usually change data which isn’t possible.From Werkzeug 0.3 onwards, the
KeyErrorraised by this class is also a subclass of theBadRequestHTTP exception and will render a page for a400 BAD REQUESTif caught in a catch-all for HTTP exceptions.- Parameters:
dicts (cabc.Iterable[MultiDict[K, V]] | None)
- class werkzeug.datastructures.ImmutableDict¶
An immutable
dict.Changelog
Added in version 0.5.
- class werkzeug.datastructures.ImmutableList(iterable=(), /)¶
An immutable
list.Changelog
Added in version 0.5.
- Private:
- class werkzeug.datastructures.FileMultiDict(mapping=None)¶
A special
MultiDictthat has convenience methods to add files to it. This is used forEnvironBuilderand generally useful for unittesting.Changelog
Added in version 0.5.
- Parameters:
mapping (MultiDict[K, V] | cabc.Mapping[K, V | list[V] | tuple[V, ...] | set[V]] | cabc.Iterable[tuple[K, V]] | None)
- add_file(name, file, filename=None, content_type=None)¶
Adds a new file to the dict.
filecan be a file name or afile-like or aFileStorageobject.- Parameters:
name (str) – the name of the field.
file (str | PathLike[str] | IO[bytes] | FileStorage) – a filename or
file-like objectfilename (str | None) – an optional filename
content_type (str | None) – an optional content type
- Return type:
None
Others¶
- class werkzeug.datastructures.FileStorage(stream=None, filename=None, name=None, content_type=None, content_length=None, headers=None)¶
The
FileStorageclass 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 dostorage.read()instead of the long formstorage.stream.read().- Parameters:
stream (t.IO[bytes] | None)
filename (str | None)
name (str | None)
content_type (str | None)
content_length (int | None)
headers (Headers | None)
- 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. Can be a
str, or an instance ofos.PathLike.
- name¶
The name of the form field.
- headers¶
The multipart headers as
Headersobject. This usually contains irrelevant information but in combination with custom multipart requests the raw headers might be interesting.Changelog
Added in version 0.6.
- property content_type: str | None¶
The content-type sent in the header. Usually not available
- property content_length: int¶
The content-length sent in the header. Usually not available
- property mimetype: str¶
Like
content_type, but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type istext/HTML; charset=utf-8the mimetype would be'text/html'.Changelog
Added in version 0.7.
- property mimetype_params: dict[str, str]¶
The mimetype parameters as dict. For example if the content type is
text/html; charset=utf-8the params would be{'charset': 'utf-8'}.Changelog
Added 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 (str | PathLike[str] | IO[bytes]) – a filename,
os.PathLike, or open file object to write to.buffer_size (int) – Passed as the
lengthparameter ofshutil.copyfileobj().
- Return type:
None
Changelog
Changed in version 1.0: Supports
pathlib.
- close()¶
Close the underlying file if possible.
- Return type:
None