structures.py 3.0 KB

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