MultiDict
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parent a032e7c · Browse files · 1 file·+357 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
1 file+357 added−0 removed
- other:+357 added−0 removed
Provenance
- Commit
e5fc88a- Tree
41cb198- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
a032e7c
1 file changed+357 added−0 removed
modified:requests/structures.py+357 added
6 unmodified lines7 Data structures that power Requests.8 9 """10 11+_missing = KeyError12 13 class CaseInsensitiveDict(dict):14 """Case-insensitive Dictionary15 49 unmodified lines65 return self.__dict__.get(key, None)66 67 def get(self, key, default=None):68 return self.__dict__.get(key, default)69+70+71+class TypeConversionDict(dict):72+ """Works like a regular dict but the :meth:`get` method can perform73+ type conversions. :class:`MultiDict` and :class:`CombinedMultiDict`74+ are subclasses of this class and provide the same feature.75+76+ .. versionadded:: 0.577+ """78+79+ def get(self, key, default=None, type=None):80+ """Return the default value if the requested data doesn't exist.81+ If `type` is provided and is a callable it should convert the value,82+ return it or raise a :exc:`ValueError` if that is not possible. In83+ this case the function will return the default as if the value was not84+ found:85+86+ >>> d = TypeConversionDict(foo='42', bar='blub')87+ >>> d.get('foo', type=int)88+ 4289+ >>> d.get('bar', -1, type=int)90+ -191+92+ :param key: The key to be looked up.93+ :param default: The default value to be returned if the key can't94+ be looked up. If not further specified `None` is95+ returned.96+ :param type: A callable that is used to cast the value in the97+ :class:`MultiDict`. If a :exc:`ValueError` is raised98+ by this callable the default value is returned.99+ """100+ try:101+ rv = self[key]102+ if type is not None:103+ rv = type(rv)104+ except (KeyError, ValueError):105+ rv = default106+ return rv107+108+109+class MultiDict(TypeConversionDict):110+ """A :class:`MultiDict` is a dictionary subclass customized to deal with111+ multiple values for the same key which is for example used by the parsing112+ functions in the wrappers. This is necessary because some HTML form113+ elements pass multiple values for the same key.114+115+ :class:`MultiDict` implements all standard dictionary methods.116+ Internally, it saves all values for a key as a list, but the standard dict117+ access methods will only return the first value for a key. If you want to118+ gain access to the other values, too, you have to use the `list` methods as119+ explained below.120+121+ Basic Usage:122+123+ >>> d = MultiDict([('a', 'b'), ('a', 'c')])124+ >>> d125+ MultiDict([('a', 'b'), ('a', 'c')])126+ >>> d['a']127+ 'b'128+ >>> d.getlist('a')129+ ['b', 'c']130+ >>> 'a' in d131+ True132+133+ It behaves like a normal dict thus all dict functions will only return the134+ first value when multiple values for one key are found.135+136+ From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a137+ subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will138+ render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP139+ exceptions.140+141+ A :class:`MultiDict` can be constructed from an iterable of142+ ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.2143+ onwards some keyword parameters.144+145+ :param mapping: the initial value for the :class:`MultiDict`. Either a146+ regular dict, an iterable of ``(key, value)`` tuples147+ or `None`.148+ """149+150+ def __init__(self, mapping=None):151+ if isinstance(mapping, MultiDict):152+ dict.__init__(self, ((k, l[:]) for k, l in mapping.iterlists()))153+ elif isinstance(mapping, dict):154+ tmp = {}155+ for key, value in mapping.iteritems():156+ if isinstance(value, (tuple, list)):157+ value = list(value)158+ else:159+ value = [value]160+ tmp[key] = value161+ dict.__init__(self, tmp)162+ else:163+ tmp = {}164+ for key, value in mapping or ():165+ tmp.setdefault(key, []).append(value)166+ dict.__init__(self, tmp)167+168+ def __getstate__(self):169+ return dict(self.lists())170+171+ def __setstate__(self, value):172+ dict.clear(self)173+ dict.update(self, value)174+175+ def __iter__(self):176+ return self.iterkeys()177+178+ def __getitem__(self, key):179+ """Return the first data value for this key;180+ raises KeyError if not found.181+182+ :param key: The key to be looked up.183+ :raise KeyError: if the key does not exist.184+ """185+ if key in self:186+ return dict.__getitem__(self, key)[0]187+ raise BadRequestKeyError(key)188+189+ def __setitem__(self, key, value):190+ """Like :meth:`add` but removes an existing key first.191+192+ :param key: the key for the value.193+ :param value: the value to set.194+ """195+ dict.__setitem__(self, key, [value])196+197+ def add(self, key, value):198+ """Adds a new value for the key.199+200+ .. versionadded:: 0.6201+202+ :param key: the key for the value.203+ :param value: the value to add.204+ """205+ dict.setdefault(self, key, []).append(value)206+207+ def getlist(self, key, type=None):208+ """Return the list of items for a given key. If that key is not in the209+ `MultiDict`, the return value will be an empty list. Just as `get`210+ `getlist` accepts a `type` parameter. All items will be converted211+ with the callable defined there.212+213+ :param key: The key to be looked up.214+ :param type: A callable that is used to cast the value in the215+ :class:`MultiDict`. If a :exc:`ValueError` is raised216+ by this callable the value will be removed from the list.217+ :return: a :class:`list` of all the values for the key.218+ """219+ try:220+ rv = dict.__getitem__(self, key)221+ except KeyError:222+ return []223+ if type is None:224+ return list(rv)225+ result = []226+ for item in rv:227+ try:228+ result.append(type(item))229+ except ValueError:230+ pass231+ return result232+233+ def setlist(self, key, new_list):234+ """Remove the old values for a key and add new ones. Note that the list235+ you pass the values in will be shallow-copied before it is inserted in236+ the dictionary.237+238+ >>> d = MultiDict()239+ >>> d.setlist('foo', ['1', '2'])240+ >>> d['foo']241+ '1'242+ >>> d.getlist('foo')243+ ['1', '2']244+245+ :param key: The key for which the values are set.246+ :param new_list: An iterable with the new values for the key. Old values247+ are removed first.248+ """249+ dict.__setitem__(self, key, list(new_list))250+251+ def setdefault(self, key, default=None):252+ """Returns the value for the key if it is in the dict, otherwise it253+ returns `default` and sets that value for `key`.254+255+ :param key: The key to be looked up.256+ :param default: The default value to be returned if the key is not257+ in the dict. If not further specified it's `None`.258+ """259+ if key not in self:260+ self[key] = default261+ else:262+ default = self[key]263+ return default264+265+ def setlistdefault(self, key, default_list=None):266+ """Like `setdefault` but sets multiple values. The list returned267+ is not a copy, but the list that is actually used internally. This268+ means that you can put new values into the dict by appending items269+ to the list:270+271+ >>> d = MultiDict({"foo": 1})272+ >>> d.setlistdefault("foo").extend([2, 3])273+ >>> d.getlist("foo")274+ [1, 2, 3]275+276+ :param key: The key to be looked up.277+ :param default: An iterable of default values. It is either copied278+ (in case it was a list) or converted into a list279+ before returned.280+ :return: a :class:`list`281+ """282+ if key not in self:283+ default_list = list(default_list or ())284+ dict.__setitem__(self, key, default_list)285+ else:286+ default_list = dict.__getitem__(self, key)287+ return default_list288+289+ def items(self, multi=False):290+ """Return a list of ``(key, value)`` pairs.291+292+ :param multi: If set to `True` the list returned will have a293+ pair for each value of each key. Otherwise it294+ will only contain pairs for the first value of295+ each key.296+297+ :return: a :class:`list`298+ """299+ return list(self.iteritems(multi))300+301+ def lists(self):302+ """Return a list of ``(key, values)`` pairs, where values is the list of303+ all values associated with the key.304+305+ :return: a :class:`list`306+ """307+ return list(self.iterlists())308+309+ def values(self):310+ """Returns a list of the first value on every key's value list.311+312+ :return: a :class:`list`.313+ """314+ return [self[key] for key in self.iterkeys()]315+316+ def listvalues(self):317+ """Return a list of all values associated with a key. Zipping318+ :meth:`keys` and this is the same as calling :meth:`lists`:319+320+ >>> d = MultiDict({"foo": [1, 2, 3]})321+ >>> zip(d.keys(), d.listvalues()) == d.lists()322+ True323+324+ :return: a :class:`list`325+ """326+ return list(self.iterlistvalues())327+328+ def iteritems(self, multi=False):329+ """Like :meth:`items` but returns an iterator."""330+ for key, values in dict.iteritems(self):331+ if multi:332+ for value in values:333+ yield key, value334+ else:335+ yield key, values[0]336+337+ def iterlists(self):338+ """Like :meth:`items` but returns an iterator."""339+ for key, values in dict.iteritems(self):340+ yield key, list(values)341+342+ def itervalues(self):343+ """Like :meth:`values` but returns an iterator."""344+ for values in dict.itervalues(self):345+ yield values[0]346+347+ def iterlistvalues(self):348+ """Like :meth:`listvalues` but returns an iterator."""349+ return dict.itervalues(self)350+351+ def copy(self):352+ """Return a shallow copy of this object."""353+ return self.__class__(self)354+355+ def to_dict(self, flat=True):356+ """Return the contents as regular dict. If `flat` is `True` the357+ returned dict will only have the first item present, if `flat` is358+ `False` all values will be returned as lists.359+360+ :param flat: If set to `False` the dict returned will have lists361+ with all the values in it. Otherwise it will only362+ contain the first value for each key.363+ :return: a :class:`dict`364+ """365+ if flat:366+ return dict(self.iteritems())367+ return dict(self.lists())368+369+ def update(self, other_dict):370+ """update() extends rather than replaces existing key lists."""371+ for key, value in iter_multi_items(other_dict):372+ MultiDict.add(self, key, value)373+374+ def pop(self, key, default=_missing):375+ """Pop the first item for a list on the dict. Afterwards the376+ key is removed from the dict, so additional values are discarded:377+378+ >>> d = MultiDict({"foo": [1, 2, 3]})379+ >>> d.pop("foo")380+ 1381+ >>> "foo" in d382+ False383+384+ :param key: the key to pop.385+ :param default: if provided the value to return if the key was386+ not in the dictionary.387+ """388+ try:389+ return dict.pop(self, key)[0]390+ except KeyError, e:391+ if default is not _missing:392+ return default393+ raise BadRequestKeyError(str(e))394+395+ def popitem(self):396+ """Pop an item from the dict."""397+ try:398+ item = dict.popitem(self)399+ return (item[0], item[1][0])400+ except KeyError, e:401+ raise BadRequestKeyError(str(e))402+403+ def poplist(self, key):404+ """Pop the list for a key from the dict. If the key is not in the dict405+ an empty list is returned.406+407+ .. versionchanged:: 0.5408+ If the key does no longer exist a list is returned instead of409+ raising an error.410+ """411+ return dict.pop(self, key, [])412+413+ def popitemlist(self):414+ """Pop a ``(key, list)`` tuple from the dict."""415+ try:416+ return dict.popitem(self)417+ except KeyError, e:418+ raise BadRequestKeyError(str(e))419+420+ def __copy__(self):421+ return self.copy()422+423+ def __repr__(self):424+ return '%s(%r)' % (self.__class__.__name__, self.items(multi=True))