You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

structures.py 2.9KB

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