cookies.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  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 calendar
  9. import collections
  10. from .compat import cookielib, urlparse, urlunparse, Morsel
  11. try:
  12. import threading
  13. # grr, pyflakes: this fixes "redefinition of unused 'threading'"
  14. threading
  15. except ImportError:
  16. import dummy_threading as threading
  17. class MockRequest(object):
  18. """Wraps a `requests.Request` to mimic a `urllib2.Request`.
  19. The code in `cookielib.CookieJar` expects this interface in order to correctly
  20. manage cookie policies, i.e., determine whether a cookie can be set, given the
  21. domains of the request and the cookie.
  22. The original request object is read-only. The client is responsible for collecting
  23. the new headers via `get_new_headers()` and interpreting them appropriately. You
  24. probably want `get_cookie_header`, defined below.
  25. """
  26. def __init__(self, request):
  27. self._r = request
  28. self._new_headers = {}
  29. self.type = urlparse(self._r.url).scheme
  30. def get_type(self):
  31. return self.type
  32. def get_host(self):
  33. return urlparse(self._r.url).netloc
  34. def get_origin_req_host(self):
  35. return self.get_host()
  36. def get_full_url(self):
  37. # Only return the response's URL if the user hadn't set the Host
  38. # header
  39. if not self._r.headers.get('Host'):
  40. return self._r.url
  41. # If they did set it, retrieve it and reconstruct the expected domain
  42. host = self._r.headers['Host']
  43. parsed = urlparse(self._r.url)
  44. # Reconstruct the URL as we expect it
  45. return urlunparse([
  46. parsed.scheme, host, parsed.path, parsed.params, parsed.query,
  47. parsed.fragment
  48. ])
  49. def is_unverifiable(self):
  50. return True
  51. def has_header(self, name):
  52. return name in self._r.headers or name in self._new_headers
  53. def get_header(self, name, default=None):
  54. return self._r.headers.get(name, self._new_headers.get(name, default))
  55. def add_header(self, key, val):
  56. """cookielib has no legitimate use for this method; add it back if you find one."""
  57. raise NotImplementedError("Cookie headers should be added with add_unredirected_header()")
  58. def add_unredirected_header(self, name, value):
  59. self._new_headers[name] = value
  60. def get_new_headers(self):
  61. return self._new_headers
  62. @property
  63. def unverifiable(self):
  64. return self.is_unverifiable()
  65. @property
  66. def origin_req_host(self):
  67. return self.get_origin_req_host()
  68. @property
  69. def host(self):
  70. return self.get_host()
  71. class MockResponse(object):
  72. """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
  73. ...what? Basically, expose the parsed HTTP headers from the server response
  74. the way `cookielib` expects to see them.
  75. """
  76. def __init__(self, headers):
  77. """Make a MockResponse for `cookielib` to read.
  78. :param headers: a httplib.HTTPMessage or analogous carrying the headers
  79. """
  80. self._headers = headers
  81. def info(self):
  82. return self._headers
  83. def getheaders(self, name):
  84. self._headers.getheaders(name)
  85. def extract_cookies_to_jar(jar, request, response):
  86. """Extract the cookies from the response into a CookieJar.
  87. :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
  88. :param request: our own requests.Request object
  89. :param response: urllib3.HTTPResponse object
  90. """
  91. if not (hasattr(response, '_original_response') and
  92. response._original_response):
  93. return
  94. # the _original_response field is the wrapped httplib.HTTPResponse object,
  95. req = MockRequest(request)
  96. # pull out the HTTPMessage with the headers and put it in the mock:
  97. res = MockResponse(response._original_response.msg)
  98. jar.extract_cookies(res, req)
  99. def get_cookie_header(jar, request):
  100. """Produce an appropriate Cookie header string to be sent with `request`, or None."""
  101. r = MockRequest(request)
  102. jar.add_cookie_header(r)
  103. return r.get_new_headers().get('Cookie')
  104. def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
  105. """Unsets a cookie by name, by default over all domains and paths.
  106. Wraps CookieJar.clear(), is O(n).
  107. """
  108. clearables = []
  109. for cookie in cookiejar:
  110. if cookie.name != name:
  111. continue
  112. if domain is not None and domain != cookie.domain:
  113. continue
  114. if path is not None and path != cookie.path:
  115. continue
  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, collections.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 __contains__(self, name):
  221. try:
  222. return super(RequestsCookieJar, self).__contains__(name)
  223. except CookieConflictError:
  224. return True
  225. def __getitem__(self, name):
  226. """Dict-like __getitem__() for compatibility with client code. Throws
  227. exception if there are more than one cookie with name. In that case,
  228. use the more explicit get() method instead.
  229. .. warning:: operation is O(n), not O(1)."""
  230. return self._find_no_duplicates(name)
  231. def __setitem__(self, name, value):
  232. """Dict-like __setitem__ for compatibility with client code. Throws
  233. exception if there is already a cookie of that name in the jar. In that
  234. case, use the more explicit set() method instead."""
  235. self.set(name, value)
  236. def __delitem__(self, name):
  237. """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
  238. ``remove_cookie_by_name()``."""
  239. remove_cookie_by_name(self, name)
  240. def set_cookie(self, cookie, *args, **kwargs):
  241. if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
  242. cookie.value = cookie.value.replace('\\"', '')
  243. return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
  244. def update(self, other):
  245. """Updates this jar with cookies from another CookieJar or dict-like"""
  246. if isinstance(other, cookielib.CookieJar):
  247. for cookie in other:
  248. self.set_cookie(copy.copy(cookie))
  249. else:
  250. super(RequestsCookieJar, self).update(other)
  251. def _find(self, name, domain=None, path=None):
  252. """Requests uses this method internally to get cookie values. Takes as
  253. args name and optional domain and path. Returns a cookie.value. If
  254. there are conflicting cookies, _find arbitrarily chooses one. See
  255. _find_no_duplicates if you want an exception thrown if there are
  256. conflicting cookies."""
  257. for cookie in iter(self):
  258. if cookie.name == name:
  259. if domain is None or cookie.domain == domain:
  260. if path is None or cookie.path == path:
  261. return cookie.value
  262. raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
  263. def _find_no_duplicates(self, name, domain=None, path=None):
  264. """Both ``__get_item__`` and ``get`` call this function: it's never
  265. used elsewhere in Requests. Takes as args name and optional domain and
  266. path. Returns a cookie.value. Throws KeyError if cookie is not found
  267. and CookieConflictError if there are multiple cookies that match name
  268. and optionally domain and path."""
  269. toReturn = None
  270. for cookie in iter(self):
  271. if cookie.name == name:
  272. if domain is None or cookie.domain == domain:
  273. if path is None or cookie.path == path:
  274. if toReturn is not None: # if there are multiple cookies that meet passed in criteria
  275. raise CookieConflictError('There are multiple cookies with name, %r' % (name))
  276. toReturn = cookie.value # we will eventually return this as long as no cookie conflict
  277. if toReturn:
  278. return toReturn
  279. raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
  280. def __getstate__(self):
  281. """Unlike a normal CookieJar, this class is pickleable."""
  282. state = self.__dict__.copy()
  283. # remove the unpickleable RLock object
  284. state.pop('_cookies_lock')
  285. return state
  286. def __setstate__(self, state):
  287. """Unlike a normal CookieJar, this class is pickleable."""
  288. self.__dict__.update(state)
  289. if '_cookies_lock' not in self.__dict__:
  290. self._cookies_lock = threading.RLock()
  291. def copy(self):
  292. """Return a copy of this RequestsCookieJar."""
  293. new_cj = RequestsCookieJar()
  294. new_cj.update(self)
  295. return new_cj
  296. def _copy_cookie_jar(jar):
  297. if jar is None:
  298. return None
  299. if hasattr(jar, 'copy'):
  300. # We're dealing with an instance of RequestsCookieJar
  301. return jar.copy()
  302. # We're dealing with a generic CookieJar instance
  303. new_jar = copy.copy(jar)
  304. new_jar.clear()
  305. for cookie in jar:
  306. new_jar.set_cookie(copy.copy(cookie))
  307. return new_jar
  308. def create_cookie(name, value, **kwargs):
  309. """Make a cookie from underspecified parameters.
  310. By default, the pair of `name` and `value` will be set for the domain ''
  311. and sent on every request (this is sometimes called a "supercookie").
  312. """
  313. result = dict(
  314. version=0,
  315. name=name,
  316. value=value,
  317. port=None,
  318. domain='',
  319. path='/',
  320. secure=False,
  321. expires=None,
  322. discard=True,
  323. comment=None,
  324. comment_url=None,
  325. rest={'HttpOnly': None},
  326. rfc2109=False,)
  327. badargs = set(kwargs) - set(result)
  328. if badargs:
  329. err = 'create_cookie() got unexpected keyword arguments: %s'
  330. raise TypeError(err % list(badargs))
  331. result.update(kwargs)
  332. result['port_specified'] = bool(result['port'])
  333. result['domain_specified'] = bool(result['domain'])
  334. result['domain_initial_dot'] = result['domain'].startswith('.')
  335. result['path_specified'] = bool(result['path'])
  336. return cookielib.Cookie(**result)
  337. def morsel_to_cookie(morsel):
  338. """Convert a Morsel object into a Cookie containing the one k/v pair."""
  339. expires = None
  340. if morsel['max-age']:
  341. try:
  342. expires = int(time.time() + int(morsel['max-age']))
  343. except ValueError:
  344. raise TypeError('max-age: %s must be integer' % morsel['max-age'])
  345. elif morsel['expires']:
  346. time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
  347. expires = calendar.timegm(
  348. time.strptime(morsel['expires'], time_template)
  349. )
  350. return create_cookie(
  351. comment=morsel['comment'],
  352. comment_url=bool(morsel['comment']),
  353. discard=False,
  354. domain=morsel['domain'],
  355. expires=expires,
  356. name=morsel.key,
  357. path=morsel['path'],
  358. port=None,
  359. rest={'HttpOnly': morsel['httponly']},
  360. rfc2109=False,
  361. secure=bool(morsel['secure']),
  362. value=morsel.value,
  363. version=morsel['version'] or 0,
  364. )
  365. def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
  366. """Returns a CookieJar from a key/value dictionary.
  367. :param cookie_dict: Dict of key/values to insert into CookieJar.
  368. :param cookiejar: (optional) A cookiejar to add the cookies to.
  369. :param overwrite: (optional) If False, will not replace cookies
  370. already in the jar with new ones.
  371. """
  372. if cookiejar is None:
  373. cookiejar = RequestsCookieJar()
  374. if cookie_dict is not None:
  375. names_from_jar = [cookie.name for cookie in cookiejar]
  376. for name in cookie_dict:
  377. if overwrite or (name not in names_from_jar):
  378. cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
  379. return cookiejar
  380. def merge_cookies(cookiejar, cookies):
  381. """Add cookies to cookiejar and returns a merged CookieJar.
  382. :param cookiejar: CookieJar object to add the cookies to.
  383. :param cookies: Dictionary or CookieJar object to be added.
  384. """
  385. if not isinstance(cookiejar, cookielib.CookieJar):
  386. raise ValueError('You can only merge into CookieJar')
  387. if isinstance(cookies, dict):
  388. cookiejar = cookiejar_from_dict(
  389. cookies, cookiejar=cookiejar, overwrite=False)
  390. elif isinstance(cookies, cookielib.CookieJar):
  391. try:
  392. cookiejar.update(cookies)
  393. except AttributeError:
  394. for cookie_in_jar in cookies:
  395. cookiejar.set_cookie(cookie_in_jar)
  396. return cookiejar