cookies.py 14 KB

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