structures.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. # -*- coding: utf-8 -*-
  2. """
  3. requests.structures
  4. ~~~~~~~~~~~~~~~~~~~
  5. Data structures that power Requests.
  6. """
  7. from .compat import OrderedDict, Mapping, MutableMapping
  8. class CaseInsensitiveDict(MutableMapping):
  9. """A case-insensitive ``dict``-like object.
  10. Implements all methods and operations of
  11. ``MutableMapping`` as well as dict's ``copy``. Also
  12. provides ``lower_items``.
  13. All keys are expected to be strings. The structure remembers the
  14. case of the last key to be set, and ``iter(instance)``,
  15. ``keys()``, ``items()``, ``iterkeys()``, and ``iteritems()``
  16. will contain case-sensitive keys. However, querying and contains
  17. testing is case insensitive::
  18. cid = CaseInsensitiveDict()
  19. cid['Accept'] = 'application/json'
  20. cid['aCCEPT'] == 'application/json' # True
  21. list(cid) == ['Accept'] # True
  22. For example, ``headers['content-encoding']`` will return the
  23. value of a ``'Content-Encoding'`` response header, regardless
  24. of how the header name was originally stored.
  25. If the constructor, ``.update``, or equality comparison
  26. operations are given keys that have equal ``.lower()``s, the
  27. behavior is undefined.
  28. """
  29. def __init__(self, data=None, **kwargs):
  30. self._store = OrderedDict()
  31. if data is None:
  32. data = {}
  33. self.update(data, **kwargs)
  34. def __setitem__(self, key, value):
  35. # Use the lowercased key for lookups, but store the actual
  36. # key alongside the value.
  37. self._store[key.lower()] = (key, value)
  38. def __getitem__(self, key):
  39. return self._store[key.lower()][1]
  40. def __delitem__(self, key):
  41. del self._store[key.lower()]
  42. def __iter__(self):
  43. return (casedkey for casedkey, mappedvalue in self._store.values())
  44. def __len__(self):
  45. return len(self._store)
  46. def lower_items(self):
  47. """Like iteritems(), but with all lowercase keys."""
  48. return (
  49. (lowerkey, keyval[1])
  50. for (lowerkey, keyval)
  51. in self._store.items()
  52. )
  53. def __eq__(self, other):
  54. if isinstance(other, Mapping):
  55. other = CaseInsensitiveDict(other)
  56. else:
  57. return NotImplemented
  58. # Compare insensitively
  59. return dict(self.lower_items()) == dict(other.lower_items())
  60. # Copy is required
  61. def copy(self):
  62. return CaseInsensitiveDict(self._store.values())
  63. def __repr__(self):
  64. return str(dict(self.items()))
  65. class LookupDict(dict):
  66. """Dictionary lookup object."""
  67. def __init__(self, name=None):
  68. self.name = name
  69. super(LookupDict, self).__init__()
  70. def __repr__(self):
  71. return '<lookup \'%s\'>' % (self.name)
  72. def __getitem__(self, key):
  73. # We allow fall-through here, so values default to None
  74. return self.__dict__.get(key, None)
  75. def get(self, key, default=None):
  76. return self.__dict__.get(key, default)