cookies.py 18 KB

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