structures.py 2.9 KB

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