Development of an internal social media platform with personalised dashboards for students
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.

_collections.py 11KB

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