cookies.py 17 KB

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