Skip to content
Myr

Merge branch 'master' into develop

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 · parents ea86602, d3a46c8 · Browse files · 2 files+368 added−1 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+368 added−1 removed

  • other:+368 added−1 removed

2 files+368 added−1 removed

added:requests/structures.py+360 added
12# from: werkzeug34class TypeConversionDict(dict):5 """Works like a regular dict but the :meth:`get` method can perform6 type conversions. :class:`MultiDict` and :class:`CombinedMultiDict`7 are subclasses of this class and provide the same feature.8 """910 def get(self, key, default=None, type=None):11 """Return the default value if the requested data doesn't exist.12 If `type` is provided and is a callable it should convert the value,13 return it or raise a :exc:`ValueError` if that is not possible. In14 this case the function will return the default as if the value was not15 found:1617 >>> d = TypeConversionDict(foo='42', bar='blub')18 >>> d.get('foo', type=int)19 4220 >>> d.get('bar', -1, type=int)21 -12223 :param key: The key to be looked up.24 :param default: The default value to be returned if the key can't25 be looked up. If not further specified `None` is26 returned.27 :param type: A callable that is used to cast the value in the28 :class:`MultiDict`. If a :exc:`ValueError` is raised29 by this callable the default value is returned.30 """31 try:32 rv = self[key]33 if type is not None:34 rv = type(rv)35 except (KeyError, ValueError):36 rv = default37 return rv38394041# from: werkzeug4243class MultiDict(TypeConversionDict):44 """A :class:`MultiDict` is a dictionary subclass customized to deal with45 multiple values for the same key which is for example used by the parsing46 functions in the wrappers. This is necessary because some HTML form47 elements pass multiple values for the same key.4849 :class:`MultiDict` implements all standard dictionary methods.50 Internally, it saves all values for a key as a list, but the standard dict51 access methods will only return the first value for a key. If you want to52 gain access to the other values, too, you have to use the `list` methods as53 explained below.5455 Basic Usage:5657 >>> d = MultiDict([('a', 'b'), ('a', 'c')])58 >>> d59 MultiDict([('a', 'b'), ('a', 'c')])60 >>> d['a']61 'b'62 >>> d.getlist('a')63 ['b', 'c']64 >>> 'a' in d65 True6667 It behaves like a normal dict thus all dict functions will only return the68 first value when multiple values for one key are found.6970 From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a71 subclass of the :exc:`~exceptions.BadRequest` HTTP exception and will72 render a page for a ``400 BAD REQUEST`` if caught in a catch-all for HTTP73 exceptions.7475 A :class:`MultiDict` can be constructed from an iterable of76 ``(key, value)`` tuples, a dict, a :class:`MultiDict` or from Werkzeug 0.277 onwards some keyword parameters.7879 :param mapping: the initial value for the :class:`MultiDict`. Either a80 regular dict, an iterable of ``(key, value)`` tuples81 or `None`.82 """8384 # the key error this class raises. Because of circular dependencies85 # with the http exception module this class is created at the end of86 # this module.87 KeyError = None8889 def __init__(self, mapping=None):90 if isinstance(mapping, MultiDict):91 dict.__init__(self, ((k, l[:]) for k, l in mapping.iterlists()))92 elif isinstance(mapping, dict):93 tmp = {}94 for key, value in mapping.iteritems():95 if isinstance(value, (tuple, list)):96 value = list(value)97 else:98 value = [value]99 tmp[key] = value100 dict.__init__(self, tmp)101 else:102 tmp = {}103 for key, value in mapping or ():104 tmp.setdefault(key, []).append(value)105 dict.__init__(self, tmp)106107 def __getstate__(self):108 return dict(self.lists())109110 def __setstate__(self, value):111 dict.clear(self)112 dict.update(self, value)113114 def __iter__(self):115 return self.iterkeys()116117 def __getitem__(self, key):118 """Return the first data value for this key;119 raises KeyError if not found.120121 :param key: The key to be looked up.122 :raise KeyError: if the key does not exist.123 """124 if key in self:125 return dict.__getitem__(self, key)[0]126 raise self.KeyError(key)127128 def __setitem__(self, key, value):129 """Like :meth:`add` but removes an existing key first.130131 :param key: the key for the value.132 :param value: the value to set.133 """134 dict.__setitem__(self, key, [value])135136 def add(self, key, value):137 """Adds a new value for the key.138139 .. versionadded:: 0.6140141 :param key: the key for the value.142 :param value: the value to add.143 """144 dict.setdefault(self, key, []).append(value)145146 def getlist(self, key, type=None):147 """Return the list of items for a given key. If that key is not in the148 `MultiDict`, the return value will be an empty list. Just as `get`149 `getlist` accepts a `type` parameter. All items will be converted150 with the callable defined there.151152 :param key: The key to be looked up.153 :param type: A callable that is used to cast the value in the154 :class:`MultiDict`. If a :exc:`ValueError` is raised155 by this callable the value will be removed from the list.156 :return: a :class:`list` of all the values for the key.157 """158 try:159 rv = dict.__getitem__(self, key)160 except KeyError:161 return []162 if type is None:163 return list(rv)164 result = []165 for item in rv:166 try:167 result.append(type(item))168 except ValueError:169 pass170 return result171172 def setlist(self, key, new_list):173 """Remove the old values for a key and add new ones. Note that the list174 you pass the values in will be shallow-copied before it is inserted in175 the dictionary.176177 >>> d = MultiDict()178 >>> d.setlist('foo', ['1', '2'])179 >>> d['foo']180 '1'181 >>> d.getlist('foo')182 ['1', '2']183184 :param key: The key for which the values are set.185 :param new_list: An iterable with the new values for the key. Old values186 are removed first.187 """188 dict.__setitem__(self, key, list(new_list))189190 def setdefault(self, key, default=None):191 """Returns the value for the key if it is in the dict, otherwise it192 returns `default` and sets that value for `key`.193194 :param key: The key to be looked up.195 :param default: The default value to be returned if the key is not196 in the dict. If not further specified it's `None`.197 """198 if key not in self:199 self[key] = default200 else:201 default = self[key]202 return default203204 def setlistdefault(self, key, default_list=None):205 """Like `setdefault` but sets multiple values. The list returned206 is not a copy, but the list that is actually used internally. This207 means that you can put new values into the dict by appending items208 to the list:209210 >>> d = MultiDict({"foo": 1})211 >>> d.setlistdefault("foo").extend([2, 3])212 >>> d.getlist("foo")213 [1, 2, 3]214215 :param key: The key to be looked up.216 :param default: An iterable of default values. It is either copied217 (in case it was a list) or converted into a list218 before returned.219 :return: a :class:`list`220 """221 if key not in self:222 default_list = list(default_list or ())223 dict.__setitem__(self, key, default_list)224 else:225 default_list = dict.__getitem__(self, key)226 return default_list227228 def items(self, multi=False):229 """Return a list of ``(key, value)`` pairs.230231 :param multi: If set to `True` the list returned will have a232 pair for each value of each key. Otherwise it233 will only contain pairs for the first value of234 each key.235236 :return: a :class:`list`237 """238 return list(self.iteritems(multi))239240 def lists(self):241 """Return a list of ``(key, values)`` pairs, where values is the list of242 all values associated with the key.243244 :return: a :class:`list`245 """246 return list(self.iterlists())247248 def values(self):249 """Returns a list of the first value on every key's value list.250251 :return: a :class:`list`.252 """253 return [self[key] for key in self.iterkeys()]254255 def listvalues(self):256 """Return a list of all values associated with a key. Zipping257 :meth:`keys` and this is the same as calling :meth:`lists`:258259 >>> d = MultiDict({"foo": [1, 2, 3]})260 >>> zip(d.keys(), d.listvalues()) == d.lists()261 True262263 :return: a :class:`list`264 """265 return list(self.iterlistvalues())266267 def iteritems(self, multi=False):268 """Like :meth:`items` but returns an iterator."""269 for key, values in dict.iteritems(self):270 if multi:271 for value in values:272 yield key, value273 else:274 yield key, values[0]275276 def iterlists(self):277 """Like :meth:`items` but returns an iterator."""278 for key, values in dict.iteritems(self):279 yield key, list(values)280281 def itervalues(self):282 """Like :meth:`values` but returns an iterator."""283 for values in dict.itervalues(self):284 yield values[0]285286 def iterlistvalues(self):287 """Like :meth:`listvalues` but returns an iterator."""288 return dict.itervalues(self)289290 def copy(self):291 """Return a shallow copy of this object."""292 return self.__class__(self)293294 def to_dict(self, flat=True):295 """Return the contents as regular dict. If `flat` is `True` the296 returned dict will only have the first item present, if `flat` is297 `False` all values will be returned as lists.298299 :param flat: If set to `False` the dict returned will have lists300 with all the values in it. Otherwise it will only301 contain the first value for each key.302 :return: a :class:`dict`303 """304 if flat:305 return dict(self.iteritems())306 return dict(self.lists())307308 def update(self, other_dict):309 """update() extends rather than replaces existing key lists."""310 for key, value in iter_multi_items(other_dict):311 MultiDict.add(self, key, value)312313 def pop(self, key, default=_missing):314 """Pop the first item for a list on the dict. Afterwards the315 key is removed from the dict, so additional values are discarded:316317 >>> d = MultiDict({"foo": [1, 2, 3]})318 >>> d.pop("foo")319 1320 >>> "foo" in d321 False322323 :param key: the key to pop.324 :param default: if provided the value to return if the key was325 not in the dictionary.326 """327 try:328 return dict.pop(self, key)[0]329 except KeyError, e:330 if default is not _missing:331 return default332 raise self.KeyError(str(e))333334 def popitem(self):335 """Pop an item from the dict."""336 try:337 item = dict.popitem(self)338 return (item[0], item[1][0])339 except KeyError, e:340 raise self.KeyError(str(e))341342 def poplist(self, key):343 """Pop the list for a key from the dict. If the key is not in the dict344 an empty list is returned.345346 .. versionchanged:: 0.5347 If the key does no longer exist a list is returned instead of348 raising an error.349 """350 return dict.pop(self, key, [])351352 def popitemlist(self):353 """Pop a ``(key, list)`` tuple from the dict."""354 try:355 return dict.popitem(self)356 except KeyError, e:357 raise self.KeyError(str(e))358359 def __repr__(self):360 return '%s(%r)' % (self.__class__.__name__, self.items(multi=True))
modified:HISTORY.rst+8 added-1 removed
1History2-------340.3.2 (2011-04-15)5++++++++++++++++++67* Automatic Decompression of GZip Encoded Content8* AutoAuth Support for Tupled HTTP Auth910110.3.1 (2011-04-01)12++++++++++++++++++1314* Cookie Changes8* Response.read() 15* Response.read()16* Poster fix1718190.3.0 (2011-02-25)
56 unmodified lines