cookies.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. # -*- coding: utf-8 -*-
  2. """
  3. Compatibility code to be able to use `cookielib.CookieJar` with requests.
  4. requests.utils imports from here, so be careful with imports.
  5. """
  6. import copy
  7. import time
  8. import collections
  9. from .compat import cookielib, urlparse, urlunparse, Morsel
  10. try:
  11. from collections import Mapping, MutableMapping
  12. except ImportError:
  13. from collections.abc import Mapping, MutableMapping
  14. try:
  15. import threading
  16. # grr, pyflakes: this fixes "redefinition of unused 'threading'"
  17. threading
  18. except ImportError:
  19. import dummy_threading as threading
  20. class MockRequest(object):
  21. """Wraps a `requests.Request` to mimic a `urllib2.Request`.
  22. The code in `cookielib.CookieJar` expects this interface in order to correctly
  23. manage cookie policies, i.e., determine whether a cookie can be set, given the
  24. domains of the request and the cookie.
  25. The original request object is read-only. The client is responsible for collecting
  26. the new headers via `get_new_headers()` and interpreting them appropriately. You
  27. probably want `get_cookie_header`, defined below.
  28. """
  29. def __init__(self, request):
  30. self._r = request
  31. self._new_headers = {}
  32. self.type = urlparse(self._r.url).scheme
  33. def get_type(self):
  34. return self.type
  35. def get_host(self):
  36. return urlparse(self._r.url).netloc
  37. def get_origin_req_host(self):
  38. return self.get_host()
  39. def get_full_url(self):
  40. # Only return the response's URL if the user hadn't set the Host
  41. # header
  42. if not self._r.headers.get('Host'):
  43. return self._r.url
  44. # If they did set it, retrieve it and reconstruct the expected domain
  45. host = self._r.headers['Host']
  46. parsed = urlparse(self._r.url)
  47. # Reconstruct the URL as we expect it
  48. return urlunparse([
  49. parsed.scheme, host, parsed.path, parsed.params, parsed.query,
  50. parsed.fragment
  51. ])
  52. def is_unverifiable(self):
  53. return True
  54. def has_header(self, name):
  55. return name in self._r.headers or name in self._new_headers
  56. def get_header(self, name, default=None):
  57. return self._r.headers.get(name, self._new_headers.get(name, default))
  58. def add_header(self, key, val):
  59. """cookielib has no legitimate use for this method; add it back if you find one."""
  60. raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")
  61. def add_unredirected_header(self, name, value):
  62. self._new_headers[name] = value
  63. def get_new_headers(self):
  64. return self._new_headers
  65. @property
  66. def unverifiable(self):
  67. return self.is_unverifiable()
  68. @property
  69. def origin_req_host(self):
  70. return self.get_origin_req_host()
  71. @property
  72. def host(self):
  73. return self.get_host()
  74. class MockResponse(object):
  75. """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
  76. ...what? Basically, expose the parsed HTTP headers from the server response
  77. the way `cookielib` expects to see them.
  78. """
  79. def __init__(self, headers):
  80. """Make a MockResponse for `cookielib` to read.
  81. :param headers: a httplib.HTTPMessage or analogous carrying the headers
  82. """
  83. self._headers = headers
  84. def info(self):
  85. return self._headers
  86. def getheaders(self, name):
  87. self._headers.getheaders(name)
  88. def extract_cookies_to_jar(jar, request, response):
  89. """Extract the cookies from the response into a CookieJar.
  90. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
  91. :param request: our own requests.Request object
  92. :param response: urllib3.HTTPResponse object
  93. """
  94. if not (hasattr(response, '_original_response') and
  95. response._original_response):
  96. return
  97. # the _original_response field is the wrapped httplib.HTTPResponse object,
  98. req = MockRequest(request)
  99. # pull out the HTTPMessage with the headers and put it in the mock:
  100. res = MockResponse(response._original_response.msg)
  101. jar.extract_cookies(res, req)
  102. def get_cookie_header(jar, request):
  103. """Produce an appropriate Cookie header string to be sent with `request`, or None."""
  104. r = MockRequest(request)
  105. jar.add_cookie_header(r)
  106. return r.get_new_headers().get('Cookie')
  107. def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
  108. """Unsets a cookie by name, by default over all domains and paths.
  109. Wraps CookieJar.clear(), is O(n).
  110. """
  111. clearables = []
  112. for cookie in cookiejar:
  113. if cookie.name == name:
  114. if domain is None or domain == cookie.domain:
  115. if path is None or path == cookie.path:
  116. clearables.append((cookie.domain, cookie.path, cookie.name))
  117. for domain, path, name in clearables:
  118. cookiejar.clear(domain, path, name)
  119. class CookieConflictError(RuntimeError):
  120. """There are two cookies that meet the criteria specified in the cookie jar.
  121. Use .get and .set and include domain and path args in order to be more specific."""
  122. class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
  123. """Compatibility class; is a cookielib.CookieJar, but exposes a dict
  124. interface.
  125. This is the CookieJar we create by default for requests and sessions that
  126. don't specify one, since some clients may expect response.cookies and
  127. session.cookies to support dict operations.
  128. Requests does not use the dict interface internally; it's just for
  129. compatibility with external client code. All requests code should work
  130. out of the box with externally provided instances of ``CookieJar``, e.g.
  131. ``LWPCookieJar`` and ``FileCookieJar``.
  132. Unlike a regular CookieJar, this class is pickleable.
  133. .. warning:: dictionary operations that are normally O(1) may be O(n).
  134. """
  135. def get(self, name, default=None, domain=None, path=None):
  136. """Dict-like get() that also supports optional domain and path args in
  137. order to resolve naming collisions from using one cookie jar over
  138. multiple domains.
  139. .. warning:: operation is O(n), not O(1)."""
  140. try:
  141. return self._find_no_duplicates(name, domain, path)
  142. except KeyError:
  143. return default
  144. def set(self, name, value, **kwargs):
  145. """Dict-like set() that also supports optional domain and path args in
  146. order to resolve naming collisions from using one cookie jar over
  147. multiple domains."""
  148. # support client code that unsets cookies by assignment of a None value:
  149. if value is None:
  150. remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
  151. return
  152. if isinstance(value, Morsel):
  153. c = morsel_to_cookie(value)
  154. else:
  155. c = create_cookie(name, value, **kwargs)
  156. self.set_cookie(c)
  157. return c
  158. def iterkeys(self):
  159. """Dict-like iterkeys() that returns an iterator of names of cookies
  160. from the jar. See itervalues() and iteritems()."""
  161. for cookie in iter(self):
  162. yield cookie.name
  163. def keys(self):
  164. """Dict-like keys() that returns a list of names of cookies from the
  165. jar. See values() and items()."""
  166. return list(self.iterkeys())
  167. def itervalues(self):
  168. """Dict-like itervalues() that returns an iterator of values of cookies
  169. from the jar. See iterkeys() and iteritems()."""
  170. for cookie in iter(self):
  171. yield cookie.value
  172. def values(self):
  173. """Dict-like values() that returns a list of values of cookies from the
  174. jar. See keys() and items()."""
  175. return list(self.itervalues())
  176. def iteritems(self):
  177. """Dict-like iteritems() that returns an iterator of name-value tuples
  178. from the jar. See iterkeys() and itervalues()."""
  179. for cookie in iter(self):
  180. yield cookie.name, cookie.value
  181. def items(self):
  182. """Dict-like items() that returns a list of name-value tuples from the
  183. jar. See keys() and values(). Allows client-code to call
  184. ``dict(RequestsCookieJar)`` and get a vanilla python dict of key value
  185. pairs."""
  186. return list(self.iteritems())
  187. def list_domains(self):
  188. """Utility method to list all the domains in the jar."""
  189. domains = []
  190. for cookie in iter(self):
  191. if cookie.domain not in domains:
  192. domains.append(cookie.domain)
  193. return domains
  194. def list_paths(self):
  195. """Utility method to list all the paths in the jar."""
  196. paths = []
  197. for cookie in iter(self):
  198. if cookie.path not in paths:
  199. paths.append(cookie.path)
  200. return paths
  201. def multiple_domains(self):
  202. """Returns True if there are multiple domains in the jar.
  203. Returns False otherwise."""
  204. domains = []
  205. for cookie in iter(self):
  206. if cookie.domain is not None and cookie.domain in domains:
  207. return True
  208. domains.append(cookie.domain)
  209. return False # there is only one domain in jar
  210. def get_dict(self, domain=None, path=None):
  211. """Takes as an argument an optional domain and path and returns a plain
  212. old Python dict of name-value pairs of cookies that meet the
  213. requirements."""
  214. dictionary = {}
  215. for cookie in iter(self):
  216. if (domain is None or cookie.domain == domain) and (path is None
  217. or cookie.path == path):
  218. dictionary[cookie.name] = cookie.value
  219. return dictionary
  220. def __getitem__(self, name):
  221. """Dict-like __getitem__() for compatibility with client code. Throws
  222. exception if there are more than one cookie with name. In that case,
  223. use the more explicit get() method instead.
  224. .. warning:: operation is O(n), not O(1)."""
  225. return self._find_no_duplicates(name)
  226. def __setitem__(self, name, value):
  227. """Dict-like __setitem__ for compatibility with client code. Throws
  228. exception if there is already a cookie of that name in the jar. In that
  229. case, use the more explicit set() method instead."""
  230. self.set(name, value)
  231. def __delitem__(self, name):
  232. """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
  233. ``remove_cookie_by_name()``."""
  234. remove_cookie_by_name(self, name)
  235. def set_cookie(self, cookie, *args, **kwargs):
  236. if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
  237. cookie.value = cookie.value.replace('\\"', '')
  238. return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
  239. def update(self, other):
  240. """Updates this jar with cookies from another CookieJar or dict-like"""
  241. if isinstance(other, cookielib.CookieJar):
  242. for cookie in other:
  243. self.set_cookie(copy.copy(cookie))
  244. else:
  245. super(RequestsCookieJar, self).update(other)
  246. def _find(self, name, domain=None, path=None):
  247. """Requests uses this method internally to get cookie values. Takes as
  248. args name and optional domain and path. Returns a cookie.value. If
  249. there are conflicting cookies, _find arbitrarily chooses one. See
  250. _find_no_duplicates if you want an exception thrown if there are
  251. conflicting cookies."""
  252. for cookie in iter(self):
  253. if cookie.name == name:
  254. if domain is None or cookie.domain == domain:
  255. if path is None or cookie.path == path:
  256. return cookie.value
  257. raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
  258. def _find_no_duplicates(self, name, domain=None, path=None):
  259. """Both ``__get_item__`` and ``get`` call this function: it's never
  260. used elsewhere in Requests. Takes as args name and optional domain and
  261. path. Returns a cookie.value. Throws KeyError if cookie is not found
  262. and CookieConflictError if there are multiple cookies that match name
  263. and optionally domain and path."""
  264. toReturn = None
  265. for cookie in iter(self):
  266. if cookie.name == name:
  267. if domain is None or cookie.domain == domain:
  268. if path is None or cookie.path == path:
  269. if toReturn is not None: # if there are multiple cookies that meet passed in criteria
  270. raise CookieConflictError('There are multiple cookies with name, %r' % (name))
  271. toReturn = cookie.value # we will eventually return this as long as no cookie conflict
  272. if toReturn:
  273. return toReturn
  274. raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
  275. def __getstate__(self):
  276. """Unlike a normal CookieJar, this class is pickleable."""
  277. state = self.__dict__.copy()
  278. # remove the unpickleable RLock object
  279. state.pop('_cookies_lock')
  280. return state
  281. def __setstate__(self, state):
  282. """Unlike a normal CookieJar, this class is pickleable."""
  283. self.__dict__.update(state)
  284. if '_cookies_lock' not in self.__dict__:
  285. self._cookies_lock = threading.RLock()
  286. def copy(self):
  287. """Return a copy of this RequestsCookieJar."""
  288. new_cj = RequestsCookieJar()
  289. new_cj.update(self)
  290. return new_cj
  291. def _copy_cookie_jar(jar):
  292. if jar is None:
  293. return None
  294. if hasattr(jar, 'copy'):
  295. # We're dealing with an instane of RequestsCookieJar
  296. return jar.copy()
  297. # We're dealing with a generic CookieJar instance
  298. new_jar = copy.copy(jar)
  299. new_jar.clear()
  300. for cookie in jar:
  301. new_jar.set_cookie(copy.copy(cookie))
  302. return new_jar
  303. def create_cookie(name, value, **kwargs):
  304. """Make a cookie from underspecified parameters.
  305. By default, the pair of `name` and `value` will be set for the domain ''
  306. and sent on every request (this is sometimes called a "supercookie").
  307. """
  308. result = dict(
  309. version=0,
  310. name=name,
  311. value=value,
  312. port=None,
  313. domain='',
  314. path='/',
  315. secure=False,
  316. expires=None,
  317. discard=True,
  318. comment=None,
  319. comment_url=None,
  320. rest={'HttpOnly': None},
  321. rfc2109=False,)
  322. badargs = set(kwargs) - set(result)
  323. if badargs:
  324. err = 'create_cookie() got unexpected keyword arguments: %s'
  325. raise TypeError(err % list(badargs))
  326. result.update(kwargs)
  327. result['port_specified'] = bool(result['port'])
  328. result['domain_specified'] = bool(result['domain'])
  329. result['domain_initial_dot'] = result['domain'].startswith('.')
  330. result['path_specified'] = bool(result['path'])
  331. return cookielib.Cookie(**result)
  332. def morsel_to_cookie(morsel):
  333. """Convert a Morsel object into a Cookie containing the one k/v pair."""
  334. expires = None
  335. if morsel['max-age']:
  336. expires = time.time() + morsel['max-age']
  337. elif morsel['expires']:
  338. time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
  339. expires = time.mktime(
  340. time.strptime(morsel['expires'], time_template)) - time.timezone
  341. return create_cookie(
  342. comment=morsel['comment'],
  343. comment_url=bool(morsel['comment']),
  344. discard=False,
  345. domain=morsel['domain'],
  346. expires=expires,
  347. name=morsel.key,
  348. path=morsel['path'],
  349. port=None,
  350. rest={'HttpOnly': morsel['httponly']},
  351. rfc2109=False,
  352. secure=bool(morsel['secure']),
  353. value=morsel.value,
  354. version=morsel['version'] or 0,
  355. )
  356. def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
  357. """Returns a CookieJar from a key/value dictionary.
  358. :param cookie_dict: Dict of key/values to insert into CookieJar.
  359. :param cookiejar: (optional) A cookiejar to add the cookies to.
  360. :param overwrite: (optional) If False, will not replace cookies
  361. already in the jar with new ones.
  362. """
  363. if cookiejar is None:
  364. cookiejar = RequestsCookieJar()
  365. if cookie_dict is not None:
  366. names_from_jar = [cookie.name for cookie in cookiejar]
  367. for name in cookie_dict:
  368. if overwrite or (name not in names_from_jar):
  369. cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
  370. return cookiejar
  371. def merge_cookies(cookiejar, cookies):
  372. """Add cookies to cookiejar and returns a merged CookieJar.
  373. :param cookiejar: CookieJar object to add the cookies to.
  374. :param cookies: Dictionary or CookieJar object to be added.
  375. """
  376. if not isinstance(cookiejar, cookielib.CookieJar):
  377. raise ValueError('You can only merge into CookieJar')
  378. if isinstance(cookies, dict):
  379. cookiejar = cookiejar_from_dict(
  380. cookies, cookiejar=cookiejar, overwrite=False)
  381. elif isinstance(cookies, cookielib.CookieJar):
  382. try:
  383. cookiejar.update(cookies)
  384. except AttributeError:
  385. for cookie_in_jar in cookies:
  386. cookiejar.set_cookie(cookie_in_jar)
  387. return cookiejar