Skip to content
Myr

no more 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 d8dcd35 · Browse files · 2 files+1 added−359 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+1 added−359 removed

  • other:+1 added−359 removed

2 files+1 added−359 removed

modified:requests/models.py+1 added-1 removed
11 unmodified lines
12from datetime import datetime13from io import BytesIO1415from .hooks import dispatch_hook, HOOKS16from .structures import CaseInsensitiveDict, MultiDict16from .structures import CaseInsensitiveDict17from .status_codes import codes1819from .auth import HTTPBasicAuth, HTTPProxyAuth20from .cookies import cookiejar_from_dict, extract_cookies_to_jar, get_cookie_header
864 unmodified lines
modified:requests/structures.py-358 removed
6 unmodified lines
7Data structures that power Requests.89"""1011_missing = KeyError1211class CaseInsensitiveDict(dict):12 """Case-insensitive Dictionary1314 For example, ``headers['content-encoding']`` will return the
48 unmodified lines
63 return self.__dict__.get(key, None)6465 def get(self, key, default=None):66 return self.__dict__.get(key, default)697071class 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.7576 .. versionadded:: 0.577 """7879 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:8586 >>> d = TypeConversionDict(foo='42', bar='blub')87 >>> d.get('foo', type=int)88 4289 >>> d.get('bar', -1, type=int)90 -19192 :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 rv107108109class 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.114115 :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.120121 Basic Usage:122123 >>> 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 True132133 It behaves like a normal dict thus all dict functions will only return the134 first value when multiple values for one key are found.135136 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.140141 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.144145 :param mapping: the initial value for the :class:`MultiDict`. Either a146 regular dict, an iterable of ``(key, value)`` tuples147 or `None`.148 """149150 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)167168 def __getstate__(self):169 return dict(self.lists())170171 def __setstate__(self, value):172 dict.clear(self)173 dict.update(self, value)174175 def __iter__(self):176 return self.iterkeys()177178 def __getitem__(self, key):179 """Return the first data value for this key;180 raises KeyError if not found.181182 :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)188189 def __setitem__(self, key, value):190 """Like :meth:`add` but removes an existing key first.191192 :param key: the key for the value.193 :param value: the value to set.194 """195 dict.__setitem__(self, key, [value])196197 def add(self, key, value):198 """Adds a new value for the key.199200 .. versionadded:: 0.6201202 :param key: the key for the value.203 :param value: the value to add.204 """205 dict.setdefault(self, key, []).append(value)206207 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.212213 :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 result232233 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.237238 >>> d = MultiDict()239 >>> d.setlist('foo', ['1', '2'])240 >>> d['foo']241 '1'242 >>> d.getlist('foo')243 ['1', '2']244245 :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))250251 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`.254255 :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 default264265 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:270271 >>> d = MultiDict({"foo": 1})272 >>> d.setlistdefault("foo").extend([2, 3])273 >>> d.getlist("foo")274 [1, 2, 3]275276 :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_list288289 def items(self, multi=False):290 """Return a list of ``(key, value)`` pairs.291292 :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.296297 :return: a :class:`list`298 """299 return list(self.iteritems(multi))300301 def lists(self):302 """Return a list of ``(key, values)`` pairs, where values is the list of303 all values associated with the key.304305 :return: a :class:`list`306 """307 return list(self.iterlists())308309 def values(self):310 """Returns a list of the first value on every key's value list.311312 :return: a :class:`list`.313 """314 return [self[key] for key in self.iterkeys()]315316 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`:319320 >>> d = MultiDict({"foo": [1, 2, 3]})321 >>> zip(d.keys(), d.listvalues()) == d.lists()322 True323324 :return: a :class:`list`325 """326 return list(self.iterlistvalues())327328 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]336337 def iterlists(self):338 """Like :meth:`items` but returns an iterator."""339 for key, values in dict.iteritems(self):340 yield key, list(values)341342 def itervalues(self):343 """Like :meth:`values` but returns an iterator."""344 for values in dict.itervalues(self):345 yield values[0]346347 def iterlistvalues(self):348 """Like :meth:`listvalues` but returns an iterator."""349 return dict.itervalues(self)350351 def copy(self):352 """Return a shallow copy of this object."""353 return self.__class__(self)354355 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.359360 :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())368369 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)373374 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:377378 >>> d = MultiDict({"foo": [1, 2, 3]})379 >>> d.pop("foo")380 1381 >>> "foo" in d382 False383384 :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))394395 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))402403 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.406407 .. 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, [])412413 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))419420 def __copy__(self):421 return self.copy()422423 def __repr__(self):424 return '%s(%r)' % (self.__class__.__name__, self.items(multi=True))