cookies.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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 interface.
  119. This is the CookieJar we create by default for requests and sessions that
  120. don't specify one, since some clients may expect response.cookies and
  121. session.cookies to support dict operations.
  122. Don't use the dict interface internally; it's just for compatibility with
  123. with external client code. All `requests` code should work out of the box
  124. with externally provided instances of CookieJar, e.g., LWPCookieJar and
  125. FileCookieJar.
  126. Caution: dictionary operations that are normally O(1) may be O(n).
  127. Unlike a regular CookieJar, this class is pickleable.
  128. """
  129. def get(self, name, default=None, domain=None, path=None):
  130. """Dict-like get() that also supports optional domain and path args in
  131. order to resolve naming collisions from using one cookie jar over
  132. multiple domains. Caution: operation is O(n), not O(1)."""
  133. try:
  134. return self._find_no_duplicates(name, domain, path)
  135. except KeyError:
  136. return default
  137. def set(self, name, value, **kwargs):
  138. """Dict-like set() that also supports optional domain and path args in
  139. order to resolve naming collisions from using one cookie jar over
  140. multiple domains."""
  141. # support client code that unsets cookies by assignment of a None value:
  142. if value is None:
  143. remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
  144. return
  145. if isinstance(value, Morsel):
  146. c = morsel_to_cookie(value)
  147. else:
  148. c = create_cookie(name, value, **kwargs)
  149. self.set_cookie(c)
  150. return c
  151. def iterkeys(self):
  152. """Dict-like iterkeys() that returns an iterator of names of cookies from the jar.
  153. See itervalues() and iteritems()."""
  154. for cookie in iter(self):
  155. yield cookie.name
  156. def keys(self):
  157. """Dict-like keys() that returns a list of names of cookies from the jar.
  158. See values() and items()."""
  159. return list(self.iterkeys())
  160. def itervalues(self):
  161. """Dict-like itervalues() that returns an iterator of values of cookies from the jar.
  162. See iterkeys() and iteritems()."""
  163. for cookie in iter(self):
  164. yield cookie.value
  165. def values(self):
  166. """Dict-like values() that returns a list of values of cookies from the jar.
  167. See keys() and items()."""
  168. return list(self.itervalues())
  169. def iteritems(self):
  170. """Dict-like iteritems() that returns an iterator of name-value tuples from the jar.
  171. See iterkeys() and itervalues()."""
  172. for cookie in iter(self):
  173. yield cookie.name, cookie.value
  174. def items(self):
  175. """Dict-like items() that returns a list of name-value tuples from the jar.
  176. See keys() and values(). Allows client-code to call "dict(RequestsCookieJar)
  177. and get a vanilla python dict of key value pairs."""
  178. return list(self.iteritems())
  179. def list_domains(self):
  180. """Utility method to list all the domains in the jar."""
  181. domains = []
  182. for cookie in iter(self):
  183. if cookie.domain not in domains:
  184. domains.append(cookie.domain)
  185. return domains
  186. def list_paths(self):
  187. """Utility method to list all the paths in the jar."""
  188. paths = []
  189. for cookie in iter(self):
  190. if cookie.path not in paths:
  191. paths.append(cookie.path)
  192. return paths
  193. def multiple_domains(self):
  194. """Returns True if there are multiple domains in the jar.
  195. Returns False otherwise."""
  196. domains = []
  197. for cookie in iter(self):
  198. if cookie.domain is not None and cookie.domain in domains:
  199. return True
  200. domains.append(cookie.domain)
  201. return False # there is only one domain in jar
  202. def get_dict(self, domain=None, path=None):
  203. """Takes as an argument an optional domain and path and returns a plain old
  204. Python dict of name-value pairs of cookies that meet the requirements."""
  205. dictionary = {}
  206. for cookie in iter(self):
  207. if (domain is None or cookie.domain == domain) and (path is None
  208. or cookie.path == path):
  209. dictionary[cookie.name] = cookie.value
  210. return dictionary
  211. def __getitem__(self, name):
  212. """Dict-like __getitem__() for compatibility with client code. Throws exception
  213. if there are more than one cookie with name. In that case, use the more
  214. explicit get() method instead. Caution: operation is O(n), not O(1)."""
  215. return self._find_no_duplicates(name)
  216. def __setitem__(self, name, value):
  217. """Dict-like __setitem__ for compatibility with client code. Throws exception
  218. if there is already a cookie of that name in the jar. In that case, use the more
  219. explicit set() method instead."""
  220. self.set(name, value)
  221. def __delitem__(self, name):
  222. """Deletes a cookie given a name. Wraps cookielib.CookieJar's remove_cookie_by_name()."""
  223. remove_cookie_by_name(self, name)
  224. def set_cookie(self, cookie, *args, **kwargs):
  225. if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
  226. cookie.value = cookie.value.replace('\\"', '')
  227. return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
  228. def update(self, other):
  229. """Updates this jar with cookies from another CookieJar or dict-like"""
  230. if isinstance(other, cookielib.CookieJar):
  231. for cookie in other:
  232. self.set_cookie(cookie)
  233. else:
  234. super(RequestsCookieJar, self).update(other)
  235. def _find(self, name, domain=None, path=None):
  236. """Requests uses this method internally to get cookie values. Takes as args name
  237. and optional domain and path. Returns a cookie.value. If there are conflicting cookies,
  238. _find arbitrarily chooses one. See _find_no_duplicates if you want an exception thrown
  239. if there are conflicting cookies."""
  240. for cookie in iter(self):
  241. if cookie.name == name:
  242. if domain is None or cookie.domain == domain:
  243. if path is None or cookie.path == path:
  244. return cookie.value
  245. raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
  246. def _find_no_duplicates(self, name, domain=None, path=None):
  247. """__get_item__ and get call _find_no_duplicates -- never used in Requests internally.
  248. Takes as args name and optional domain and path. Returns a cookie.value.
  249. Throws KeyError if cookie is not found and CookieConflictError if there are
  250. multiple cookies that match name and optionally domain and path."""
  251. toReturn = None
  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. if toReturn is not None: # if there are multiple cookies that meet passed in criteria
  257. raise CookieConflictError('There are multiple cookies with name, %r' % (name))
  258. toReturn = cookie.value # we will eventually return this as long as no cookie conflict
  259. if toReturn:
  260. return toReturn
  261. raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
  262. def __getstate__(self):
  263. """Unlike a normal CookieJar, this class is pickleable."""
  264. state = self.__dict__.copy()
  265. # remove the unpickleable RLock object
  266. state.pop('_cookies_lock')
  267. return state
  268. def __setstate__(self, state):
  269. """Unlike a normal CookieJar, this class is pickleable."""
  270. self.__dict__.update(state)
  271. if '_cookies_lock' not in self.__dict__:
  272. self._cookies_lock = threading.RLock()
  273. def copy(self):
  274. """Return a copy of this RequestsCookieJar."""
  275. new_cj = RequestsCookieJar()
  276. new_cj.update(self)
  277. return new_cj
  278. def create_cookie(name, value, **kwargs):
  279. """Make a cookie from underspecified parameters.
  280. By default, the pair of `name` and `value` will be set for the domain ''
  281. and sent on every request (this is sometimes called a "supercookie").
  282. """
  283. result = dict(
  284. version=0,
  285. name=name,
  286. value=value,
  287. port=None,
  288. domain='',
  289. path='/',
  290. secure=False,
  291. expires=None,
  292. discard=True,
  293. comment=None,
  294. comment_url=None,
  295. rest={'HttpOnly': None},
  296. rfc2109=False,)
  297. badargs = set(kwargs) - set(result)
  298. if badargs:
  299. err = 'create_cookie() got unexpected keyword arguments: %s'
  300. raise TypeError(err % list(badargs))
  301. result.update(kwargs)
  302. result['port_specified'] = bool(result['port'])
  303. result['domain_specified'] = bool(result['domain'])
  304. result['domain_initial_dot'] = result['domain'].startswith('.')
  305. result['path_specified'] = bool(result['path'])
  306. return cookielib.Cookie(**result)
  307. def morsel_to_cookie(morsel):
  308. """Convert a Morsel object into a Cookie containing the one k/v pair."""
  309. expires = None
  310. if morsel['max-age']:
  311. expires = time.time() + morsel['max-age']
  312. elif morsel['expires']:
  313. time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
  314. expires = time.mktime(
  315. time.strptime(morsel['expires'], time_template)) - time.timezone
  316. return create_cookie(
  317. comment=morsel['comment'],
  318. comment_url=bool(morsel['comment']),
  319. discard=False,
  320. domain=morsel['domain'],
  321. expires=expires,
  322. name=morsel.key,
  323. path=morsel['path'],
  324. port=None,
  325. rest={'HttpOnly': morsel['httponly']},
  326. rfc2109=False,
  327. secure=bool(morsel['secure']),
  328. value=morsel.value,
  329. version=morsel['version'] or 0,
  330. )
  331. def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
  332. """Returns a CookieJar from a key/value dictionary.
  333. :param cookie_dict: Dict of key/values to insert into CookieJar.
  334. :param cookiejar: (optional) A cookiejar to add the cookies to.
  335. :param overwrite: (optional) If False, will not replace cookies
  336. already in the jar with new ones.
  337. """
  338. if cookiejar is None:
  339. cookiejar = RequestsCookieJar()
  340. if cookie_dict is not None:
  341. names_from_jar = [cookie.name for cookie in cookiejar]
  342. for name in cookie_dict:
  343. if overwrite or (name not in names_from_jar):
  344. cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
  345. return cookiejar
  346. def merge_cookies(cookiejar, cookies):
  347. """Add cookies to cookiejar and returns a merged CookieJar.
  348. :param cookiejar: CookieJar object to add the cookies to.
  349. :param cookies: Dictionary or CookieJar object to be added.
  350. """
  351. if not isinstance(cookiejar, cookielib.CookieJar):
  352. raise ValueError('You can only merge into CookieJar')
  353. if isinstance(cookies, dict):
  354. cookiejar = cookiejar_from_dict(
  355. cookies, cookiejar=cookiejar, overwrite=False)
  356. elif isinstance(cookies, cookielib.CookieJar):
  357. try:
  358. cookiejar.update(cookies)
  359. except AttributeError:
  360. for cookie_in_jar in cookies:
  361. cookiejar.set_cookie(cookie_in_jar)
  362. return cookiejar