structures.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. """
  2. requests.structures
  3. ~~~~~~~~~~~~~~~~~~~
  4. Data structures that power Requests.
  5. """
  6. from __future__ import annotations
  7. from collections import OrderedDict
  8. from collections.abc import Iterable, Iterator, Mapping
  9. from typing import Any, Generic, TypeVar, overload
  10. from .compat import MutableMapping
  11. _VT = TypeVar("_VT")
  12. _D = TypeVar("_D")
  13. class CaseInsensitiveDict(MutableMapping[str, _VT], Generic[_VT]):
  14. """A case-insensitive ``dict``-like object.
  15. Implements all methods and operations of
  16. ``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. _store: OrderedDict[str, tuple[str, _VT]]
  35. def __init__(
  36. self,
  37. data: Mapping[str, _VT] | Iterable[tuple[str, _VT]] | None = None,
  38. **kwargs: _VT,
  39. ) -> None:
  40. self._store = OrderedDict()
  41. if data is None:
  42. data = {}
  43. self.update(data, **kwargs)
  44. def __setitem__(self, key: str, value: _VT) -> None:
  45. # Use the lowercased key for lookups, but store the actual
  46. # key alongside the value.
  47. self._store[key.lower()] = (key, value)
  48. def __getitem__(self, key: str) -> _VT:
  49. return self._store[key.lower()][1]
  50. def __delitem__(self, key: str) -> None:
  51. del self._store[key.lower()]
  52. def __iter__(self) -> Iterator[str]:
  53. return (casedkey for casedkey, _ in self._store.values())
  54. def __len__(self) -> int:
  55. return len(self._store)
  56. def lower_items(self) -> Iterator[tuple[str, _VT]]:
  57. """Like iteritems(), but with all lowercase keys."""
  58. return ((lowerkey, keyval[1]) for (lowerkey, keyval) in self._store.items())
  59. def __eq__(self, other: object) -> bool:
  60. if isinstance(other, Mapping):
  61. other_dict: CaseInsensitiveDict[Any] = CaseInsensitiveDict(other) # type: ignore[reportUnknownArgumentType]
  62. else:
  63. return NotImplemented
  64. # Compare insensitively
  65. return dict(self.lower_items()) == dict(other_dict.lower_items())
  66. # Copy is required
  67. def copy(self) -> CaseInsensitiveDict[_VT]:
  68. return CaseInsensitiveDict(self._store.values())
  69. def __repr__(self) -> str:
  70. return str(dict(self.items()))
  71. class LookupDict(dict[str, _VT]):
  72. """Dictionary lookup object."""
  73. name: Any
  74. def __init__(self, name: Any = None) -> None:
  75. self.name = name
  76. super().__init__()
  77. def __repr__(self) -> str:
  78. return f"<lookup '{self.name}'>"
  79. def __getattr__(self, key: str) -> _VT | None:
  80. # We need this for type checkers to infer typing
  81. # on attribute access with status_codes.py
  82. if key in self.__dict__:
  83. return self.__dict__[key]
  84. else:
  85. raise AttributeError(
  86. f"'{type(self).__name__}' object has no attribute '{key}'"
  87. )
  88. def __getitem__(self, key: str) -> _VT | None: # type: ignore[override]
  89. # We allow fall-through here, so values default to None
  90. return self.__dict__.get(key, None)
  91. @overload
  92. def get(self, key: str, default: None = None) -> _VT | None: ...
  93. @overload
  94. def get(self, key: str, default: _D | _VT) -> _D | _VT: ...
  95. def get(self, key: str, default: _D | None = None) -> _VT | _D | None:
  96. return self.__dict__.get(key, default)