_collections.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. from __future__ import absolute_import
  2. try:
  3. from collections.abc import Mapping, MutableMapping
  4. except ImportError:
  5. from collections import Mapping, MutableMapping
  6. try:
  7. from threading import RLock
  8. except ImportError: # Platform-specific: No threads available
  9. class RLock:
  10. def __enter__(self):
  11. pass
  12. def __exit__(self, exc_type, exc_value, traceback):
  13. pass
  14. from collections import OrderedDict
  15. from .exceptions import InvalidHeader
  16. from .packages.six import iterkeys, itervalues, PY3
  17. __all__ = ['RecentlyUsedContainer', 'HTTPHeaderDict']
  18. _Null = object()
  19. class RecentlyUsedContainer(MutableMapping):
  20. """
  21. Provides a thread-safe dict-like container which maintains up to
  22. ``maxsize`` keys while throwing away the least-recently-used keys beyond
  23. ``maxsize``.
  24. :param maxsize:
  25. Maximum number of recent elements to retain.
  26. :param dispose_func:
  27. Every time an item is evicted from the container,
  28. ``dispose_func(value)`` is called. Callback which will get called
  29. """
  30. ContainerCls = OrderedDict
  31. def __init__(self, maxsize=10, dispose_func=None):
  32. self._maxsize = maxsize
  33. self.dispose_func = dispose_func
  34. self._container = self.ContainerCls()
  35. self.lock = RLock()
  36. def __getitem__(self, key):
  37. # Re-insert the item, moving it to the end of the eviction line.
  38. with self.lock:
  39. item = self._container.pop(key)
  40. self._container[key] = item
  41. return item
  42. def __setitem__(self, key, value):
  43. evicted_value = _Null
  44. with self.lock:
  45. # Possibly evict the existing value of 'key'
  46. evicted_value = self._container.get(key, _Null)
  47. self._container[key] = value
  48. # If we didn't evict an existing value, we might have to evict the
  49. # least recently used item from the beginning of the container.
  50. if len(self._container) > self._maxsize:
  51. _key, evicted_value = self._container.popitem(last=False)
  52. if self.dispose_func and evicted_value is not _Null:
  53. self.dispose_func(evicted_value)
  54. def __delitem__(self, key):
  55. with self.lock:
  56. value = self._container.pop(key)
  57. if self.dispose_func:
  58. self.dispose_func(value)
  59. def __len__(self):
  60. with self.lock:
  61. return len(self._container)
  62. def __iter__(self):
  63. raise NotImplementedError('Iteration over this class is unlikely to be threadsafe.')
  64. def clear(self):
  65. with self.lock:
  66. # Copy pointers to all values, then wipe the mapping
  67. values = list(itervalues(self._container))
  68. self._container.clear()
  69. if self.dispose_func:
  70. for value in values:
  71. self.dispose_func(value)
  72. def keys(self):
  73. with self.lock:
  74. return list(iterkeys(self._container))
  75. class HTTPHeaderDict(MutableMapping):
  76. """
  77. :param headers:
  78. An iterable of field-value pairs. Must not contain multiple field names
  79. when compared case-insensitively.
  80. :param kwargs:
  81. Additional field-value pairs to pass in to ``dict.update``.
  82. A ``dict`` like container for storing HTTP Headers.
  83. Field names are stored and compared case-insensitively in compliance with
  84. RFC 7230. Iteration provides the first case-sensitive key seen for each
  85. case-insensitive pair.
  86. Using ``__setitem__`` syntax overwrites fields that compare equal
  87. case-insensitively in order to maintain ``dict``'s api. For fields that
  88. compare equal, instead create a new ``HTTPHeaderDict`` and use ``.add``
  89. in a loop.
  90. If multiple fields that are equal case-insensitively are passed to the
  91. constructor or ``.update``, the behavior is undefined and some will be
  92. lost.
  93. >>> headers = HTTPHeaderDict()
  94. >>> headers.add('Set-Cookie', 'foo=bar')
  95. >>> headers.add('set-cookie', 'baz=quxx')
  96. >>> headers['content-length'] = '7'
  97. >>> headers['SET-cookie']
  98. 'foo=bar, baz=quxx'
  99. >>> headers['Content-Length']
  100. '7'
  101. """
  102. def __init__(self, headers=None, **kwargs):
  103. super(HTTPHeaderDict, self).__init__()
  104. self._container = OrderedDict()
  105. if headers is not None:
  106. if isinstance(headers, HTTPHeaderDict):
  107. self._copy_from(headers)
  108. else:
  109. self.extend(headers)
  110. if kwargs:
  111. self.extend(kwargs)
  112. def __setitem__(self, key, val):
  113. self._container[key.lower()] = [key, val]
  114. return self._container[key.lower()]
  115. def __getitem__(self, key):
  116. val = self._container[key.lower()]
  117. return ', '.join(val[1:])
  118. def __delitem__(self, key):
  119. del self._container[key.lower()]
  120. def __contains__(self, key):
  121. return key.lower() in self._container
  122. def __eq__(self, other):
  123. if not isinstance(other, Mapping) and not hasattr(other, 'keys'):
  124. return False
  125. if not isinstance(other, type(self)):
  126. other = type(self)(other)
  127. return (dict((k.lower(), v) for k, v in self.itermerged()) ==
  128. dict((k.lower(), v) for k, v in other.itermerged()))
  129. def __ne__(self, other):
  130. return not self.__eq__(other)
  131. if not PY3: # Python 2
  132. iterkeys = MutableMapping.iterkeys
  133. itervalues = MutableMapping.itervalues
  134. __marker = object()
  135. def __len__(self):
  136. return len(self._container)
  137. def __iter__(self):
  138. # Only provide the originally cased names
  139. for vals in self._container.values():
  140. yield vals[0]
  141. def pop(self, key, default=__marker):
  142. '''D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
  143. If key is not found, d is returned if given, otherwise KeyError is raised.
  144. '''
  145. # Using the MutableMapping function directly fails due to the private marker.
  146. # Using ordinary dict.pop would expose the internal structures.
  147. # So let's reinvent the wheel.
  148. try:
  149. value = self[key]
  150. except KeyError:
  151. if default is self.__marker:
  152. raise
  153. return default
  154. else:
  155. del self[key]
  156. return value
  157. def discard(self, key):
  158. try:
  159. del self[key]
  160. except KeyError:
  161. pass
  162. def add(self, key, val):
  163. """Adds a (name, value) pair, doesn't overwrite the value if it already
  164. exists.
  165. >>> headers = HTTPHeaderDict(foo='bar')
  166. >>> headers.add('Foo', 'baz')
  167. >>> headers['foo']
  168. 'bar, baz'
  169. """
  170. key_lower = key.lower()
  171. new_vals = [key, val]
  172. # Keep the common case aka no item present as fast as possible
  173. vals = self._container.setdefault(key_lower, new_vals)
  174. if new_vals is not vals:
  175. vals.append(val)
  176. def extend(self, *args, **kwargs):
  177. """Generic import function for any type of header-like object.
  178. Adapted version of MutableMapping.update in order to insert items
  179. with self.add instead of self.__setitem__
  180. """
  181. if len(args) > 1:
  182. raise TypeError("extend() takes at most 1 positional "
  183. "arguments ({0} given)".format(len(args)))
  184. other = args[0] if len(args) >= 1 else ()
  185. if isinstance(other, HTTPHeaderDict):
  186. for key, val in other.iteritems():
  187. self.add(key, val)
  188. elif isinstance(other, Mapping):
  189. for key in other:
  190. self.add(key, other[key])
  191. elif hasattr(other, "keys"):
  192. for key in other.keys():
  193. self.add(key, other[key])
  194. else:
  195. for key, value in other:
  196. self.add(key, value)
  197. for key, value in kwargs.items():
  198. self.add(key, value)
  199. def getlist(self, key, default=__marker):
  200. """Returns a list of all the values for the named field. Returns an
  201. empty list if the key doesn't exist."""
  202. try:
  203. vals = self._container[key.lower()]
  204. except KeyError:
  205. if default is self.__marker:
  206. return []
  207. return default
  208. else:
  209. return vals[1:]
  210. # Backwards compatibility for httplib
  211. getheaders = getlist
  212. getallmatchingheaders = getlist
  213. iget = getlist
  214. # Backwards compatibility for http.cookiejar
  215. get_all = getlist
  216. def __repr__(self):
  217. return "%s(%s)" % (type(self).__name__, dict(self.itermerged()))
  218. def _copy_from(self, other):
  219. for key in other:
  220. val = other.getlist(key)
  221. if isinstance(val, list):
  222. # Don't need to convert tuples
  223. val = list(val)
  224. self._container[key.lower()] = [key] + val
  225. def copy(self):
  226. clone = type(self)()
  227. clone._copy_from(self)
  228. return clone
  229. def iteritems(self):
  230. """Iterate over all header lines, including duplicate ones."""
  231. for key in self:
  232. vals = self._container[key.lower()]
  233. for val in vals[1:]:
  234. yield vals[0], val
  235. def itermerged(self):
  236. """Iterate over all headers, merging duplicate ones together."""
  237. for key in self:
  238. val = self._container[key.lower()]
  239. yield val[0], ', '.join(val[1:])
  240. def items(self):
  241. return list(self.iteritems())
  242. @classmethod
  243. def from_httplib(cls, message): # Python 2
  244. """Read headers from a Python 2 httplib message object."""
  245. # python2.7 does not expose a proper API for exporting multiheaders
  246. # efficiently. This function re-reads raw lines from the message
  247. # object and extracts the multiheaders properly.
  248. obs_fold_continued_leaders = (' ', '\t')
  249. headers = []
  250. for line in message.headers:
  251. if line.startswith(obs_fold_continued_leaders):
  252. if not headers:
  253. # We received a header line that starts with OWS as described
  254. # in RFC-7230 S3.2.4. This indicates a multiline header, but
  255. # there exists no previous header to which we can attach it.
  256. raise InvalidHeader(
  257. 'Header continuation with no previous header: %s' % line
  258. )
  259. else:
  260. key, value = headers[-1]
  261. headers[-1] = (key, value + ' ' + line.strip())
  262. continue
  263. key, value = line.split(':', 1)
  264. headers.append((key, value.strip()))
  265. return cls(headers)