1 # -*- coding: utf-8 -*-
7 Data structures that power Requests.
13 from .compat import OrderedDict
16 class CaseInsensitiveDict(collections.MutableMapping):
18 A case-insensitive ``dict``-like object.
20 Implements all methods and operations of
21 ``collections.MutableMapping`` as well as dict's ``copy``. Also
22 provides ``lower_items``.
24 All keys are expected to be strings. The structure remembers the
25 case of the last key to be set, and ``iter(instance)``,
26 ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
27 will contain case-sensitive keys. However, querying and contains
28 testing is case insensitive::
30 cid = CaseInsensitiveDict()
31 cid['Accept'] = 'application/json'
32 cid['aCCEPT'] == 'application/json' # True
33 list(cid) == ['Accept'] # True
35 For example, ``headers['content-encoding']`` will return the
36 value of a ``'Content-Encoding'`` response header, regardless
37 of how the header name was originally stored.
39 If the constructor, ``.update``, or equality comparison
40 operations are given keys that have equal ``.lower()``s, the
41 behavior is undefined.
44 def __init__(self, data=None, **kwargs):
45 self._store = OrderedDict()
48 self.update(data, **kwargs)
50 def __setitem__(self, key, value):
51 # Use the lowercased key for lookups, but store the actual
52 # key alongside the value.
53 self._store[key.lower()] = (key, value)
55 def __getitem__(self, key):
56 return self._store[key.lower()][1]
58 def __delitem__(self, key):
59 del self._store[key.lower()]
62 return (casedkey for casedkey, mappedvalue in self._store.values())
65 return len(self._store)
67 def lower_items(self):
68 """Like iteritems(), but with all lowercase keys."""
71 for (lowerkey, keyval)
72 in self._store.items()
75 def __eq__(self, other):
76 if isinstance(other, collections.Mapping):
77 other = CaseInsensitiveDict(other)
80 # Compare insensitively
81 return dict(self.lower_items()) == dict(other.lower_items())
85 return CaseInsensitiveDict(self._store.values())
88 return str(dict(self.items()))
90 class LookupDict(dict):
91 """Dictionary lookup object."""
93 def __init__(self, name=None):
95 super(LookupDict, self).__init__()
98 return '<lookup \'%s\'>' % (self.name)
100 def __getitem__(self, key):
101 # We allow fall-through here, so values default to None
103 return self.__dict__.get(key, None)
105 def get(self, key, default=None):
106 return self.__dict__.get(key, default)