Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

cookies.py 18KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  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. from ._internal_utils import to_native_string
  12. from .compat import cookielib, urlparse, urlunparse, Morsel, MutableMapping
  13. try:
  14. import 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 = to_native_string(self._r.headers['Host'], encoding='utf-8')
  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. """
  101. Produce an appropriate Cookie header string to be sent with `request`, or None.
  102. :rtype: str
  103. """
  104. r = MockRequest(request)
  105. jar.add_cookie_header(r)
  106. return r.get_new_headers().get('Cookie')
  107. def remove_cookie_by_name(cookiejar, name, domain=None, path=None):
  108. """Unsets a cookie by name, by default over all domains and paths.
  109. Wraps CookieJar.clear(), is O(n).
  110. """
  111. clearables = []
  112. for cookie in cookiejar:
  113. if cookie.name != name:
  114. continue
  115. if domain is not None and domain != cookie.domain:
  116. continue
  117. if path is not None and path != cookie.path:
  118. continue
  119. clearables.append((cookie.domain, cookie.path, cookie.name))
  120. for domain, path, name in clearables:
  121. cookiejar.clear(domain, path, name)
  122. class CookieConflictError(RuntimeError):
  123. """There are two cookies that meet the criteria specified in the cookie jar.
  124. Use .get and .set and include domain and path args in order to be more specific.
  125. """
  126. class RequestsCookieJar(cookielib.CookieJar, MutableMapping):
  127. """Compatibility class; is a cookielib.CookieJar, but exposes a dict
  128. interface.
  129. This is the CookieJar we create by default for requests and sessions that
  130. don't specify one, since some clients may expect response.cookies and
  131. session.cookies to support dict operations.
  132. Requests does not use the dict interface internally; it's just for
  133. compatibility with external client code. All requests code should work
  134. out of the box with externally provided instances of ``CookieJar``, e.g.
  135. ``LWPCookieJar`` and ``FileCookieJar``.
  136. Unlike a regular CookieJar, this class is pickleable.
  137. .. warning:: dictionary operations that are normally O(1) may be O(n).
  138. """
  139. def get(self, name, default=None, domain=None, path=None):
  140. """Dict-like get() 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. .. warning:: operation is O(n), not O(1).
  144. """
  145. try:
  146. return self._find_no_duplicates(name, domain, path)
  147. except KeyError:
  148. return default
  149. def set(self, name, value, **kwargs):
  150. """Dict-like set() that also supports optional domain and path args in
  151. order to resolve naming collisions from using one cookie jar over
  152. multiple domains.
  153. """
  154. # support client code that unsets cookies by assignment of a None value:
  155. if value is None:
  156. remove_cookie_by_name(self, name, domain=kwargs.get('domain'), path=kwargs.get('path'))
  157. return
  158. if isinstance(value, Morsel):
  159. c = morsel_to_cookie(value)
  160. else:
  161. c = create_cookie(name, value, **kwargs)
  162. self.set_cookie(c)
  163. return c
  164. def iterkeys(self):
  165. """Dict-like iterkeys() that returns an iterator of names of cookies
  166. from the jar.
  167. .. seealso:: itervalues() and iteritems().
  168. """
  169. for cookie in iter(self):
  170. yield cookie.name
  171. def keys(self):
  172. """Dict-like keys() that returns a list of names of cookies from the
  173. jar.
  174. .. seealso:: values() and items().
  175. """
  176. return list(self.iterkeys())
  177. def itervalues(self):
  178. """Dict-like itervalues() that returns an iterator of values of cookies
  179. from the jar.
  180. .. seealso:: iterkeys() and iteritems().
  181. """
  182. for cookie in iter(self):
  183. yield cookie.value
  184. def values(self):
  185. """Dict-like values() that returns a list of values of cookies from the
  186. jar.
  187. .. seealso:: keys() and items().
  188. """
  189. return list(self.itervalues())
  190. def iteritems(self):
  191. """Dict-like iteritems() that returns an iterator of name-value tuples
  192. from the jar.
  193. .. seealso:: iterkeys() and itervalues().
  194. """
  195. for cookie in iter(self):
  196. yield cookie.name, cookie.value
  197. def items(self):
  198. """Dict-like items() that returns a list of name-value tuples from the
  199. jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
  200. vanilla python dict of key value pairs.
  201. .. seealso:: keys() and values().
  202. """
  203. return list(self.iteritems())
  204. def list_domains(self):
  205. """Utility method to list all the domains in the jar."""
  206. domains = []
  207. for cookie in iter(self):
  208. if cookie.domain not in domains:
  209. domains.append(cookie.domain)
  210. return domains
  211. def list_paths(self):
  212. """Utility method to list all the paths in the jar."""
  213. paths = []
  214. for cookie in iter(self):
  215. if cookie.path not in paths:
  216. paths.append(cookie.path)
  217. return paths
  218. def multiple_domains(self):
  219. """Returns True if there are multiple domains in the jar.
  220. Returns False otherwise.
  221. :rtype: bool
  222. """
  223. domains = []
  224. for cookie in iter(self):
  225. if cookie.domain is not None and cookie.domain in domains:
  226. return True
  227. domains.append(cookie.domain)
  228. return False # there is only one domain in jar
  229. def get_dict(self, domain=None, path=None):
  230. """Takes as an argument an optional domain and path and returns a plain
  231. old Python dict of name-value pairs of cookies that meet the
  232. requirements.
  233. :rtype: dict
  234. """
  235. dictionary = {}
  236. for cookie in iter(self):
  237. if (
  238. (domain is None or cookie.domain == domain) and
  239. (path is None or cookie.path == path)
  240. ):
  241. dictionary[cookie.name] = cookie.value
  242. return dictionary
  243. def __contains__(self, name):
  244. try:
  245. return super(RequestsCookieJar, self).__contains__(name)
  246. except CookieConflictError:
  247. return True
  248. def __getitem__(self, name):
  249. """Dict-like __getitem__() for compatibility with client code. Throws
  250. exception if there are more than one cookie with name. In that case,
  251. use the more explicit get() method instead.
  252. .. warning:: operation is O(n), not O(1).
  253. """
  254. return self._find_no_duplicates(name)
  255. def __setitem__(self, name, value):
  256. """Dict-like __setitem__ for compatibility with client code. Throws
  257. exception if there is already a cookie of that name in the jar. In that
  258. case, use the more explicit set() method instead.
  259. """
  260. self.set(name, value)
  261. def __delitem__(self, name):
  262. """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
  263. ``remove_cookie_by_name()``.
  264. """
  265. remove_cookie_by_name(self, name)
  266. def set_cookie(self, cookie, *args, **kwargs):
  267. if hasattr(cookie.value, 'startswith') and cookie.value.startswith('"') and cookie.value.endswith('"'):
  268. cookie.value = cookie.value.replace('\\"', '')
  269. return super(RequestsCookieJar, self).set_cookie(cookie, *args, **kwargs)
  270. def update(self, other):
  271. """Updates this jar with cookies from another CookieJar or dict-like"""
  272. if isinstance(other, cookielib.CookieJar):
  273. for cookie in other:
  274. self.set_cookie(copy.copy(cookie))
  275. else:
  276. super(RequestsCookieJar, self).update(other)
  277. def _find(self, name, domain=None, path=None):
  278. """Requests uses this method internally to get cookie values.
  279. If there are conflicting cookies, _find arbitrarily chooses one.
  280. See _find_no_duplicates if you want an exception thrown if there are
  281. conflicting cookies.
  282. :param name: a string containing name of cookie
  283. :param domain: (optional) string containing domain of cookie
  284. :param path: (optional) string containing path of cookie
  285. :return: cookie.value
  286. """
  287. for cookie in iter(self):
  288. if cookie.name == name:
  289. if domain is None or cookie.domain == domain:
  290. if path is None or cookie.path == path:
  291. return cookie.value
  292. raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
  293. def _find_no_duplicates(self, name, domain=None, path=None):
  294. """Both ``__get_item__`` and ``get`` call this function: it's never
  295. used elsewhere in Requests.
  296. :param name: a string containing name of cookie
  297. :param domain: (optional) string containing domain of cookie
  298. :param path: (optional) string containing path of cookie
  299. :raises KeyError: if cookie is not found
  300. :raises CookieConflictError: if there are multiple cookies
  301. that match name and optionally domain and path
  302. :return: cookie.value
  303. """
  304. toReturn = None
  305. for cookie in iter(self):
  306. if cookie.name == name:
  307. if domain is None or cookie.domain == domain:
  308. if path is None or cookie.path == path:
  309. if toReturn is not None: # if there are multiple cookies that meet passed in criteria
  310. raise CookieConflictError('There are multiple cookies with name, %r' % (name))
  311. toReturn = cookie.value # we will eventually return this as long as no cookie conflict
  312. if toReturn:
  313. return toReturn
  314. raise KeyError('name=%r, domain=%r, path=%r' % (name, domain, path))
  315. def __getstate__(self):
  316. """Unlike a normal CookieJar, this class is pickleable."""
  317. state = self.__dict__.copy()
  318. # remove the unpickleable RLock object
  319. state.pop('_cookies_lock')
  320. return state
  321. def __setstate__(self, state):
  322. """Unlike a normal CookieJar, this class is pickleable."""
  323. self.__dict__.update(state)
  324. if '_cookies_lock' not in self.__dict__:
  325. self._cookies_lock = threading.RLock()
  326. def copy(self):
  327. """Return a copy of this RequestsCookieJar."""
  328. new_cj = RequestsCookieJar()
  329. new_cj.set_policy(self.get_policy())
  330. new_cj.update(self)
  331. return new_cj
  332. def get_policy(self):
  333. """Return the CookiePolicy instance used."""
  334. return self._policy
  335. def _copy_cookie_jar(jar):
  336. if jar is None:
  337. return None
  338. if hasattr(jar, 'copy'):
  339. # We're dealing with an instance of RequestsCookieJar
  340. return jar.copy()
  341. # We're dealing with a generic CookieJar instance
  342. new_jar = copy.copy(jar)
  343. new_jar.clear()
  344. for cookie in jar:
  345. new_jar.set_cookie(copy.copy(cookie))
  346. return new_jar
  347. def create_cookie(name, value, **kwargs):
  348. """Make a cookie from underspecified parameters.
  349. By default, the pair of `name` and `value` will be set for the domain ''
  350. and sent on every request (this is sometimes called a "supercookie").
  351. """
  352. result = dict(
  353. version=0,
  354. name=name,
  355. value=value,
  356. port=None,
  357. domain='',
  358. path='/',
  359. secure=False,
  360. expires=None,
  361. discard=True,
  362. comment=None,
  363. comment_url=None,
  364. rest={'HttpOnly': None},
  365. rfc2109=False,)
  366. badargs = set(kwargs) - set(result)
  367. if badargs:
  368. err = 'create_cookie() got unexpected keyword arguments: %s'
  369. raise TypeError(err % list(badargs))
  370. result.update(kwargs)
  371. result['port_specified'] = bool(result['port'])
  372. result['domain_specified'] = bool(result['domain'])
  373. result['domain_initial_dot'] = result['domain'].startswith('.')
  374. result['path_specified'] = bool(result['path'])
  375. return cookielib.Cookie(**result)
  376. def morsel_to_cookie(morsel):
  377. """Convert a Morsel object into a Cookie containing the one k/v pair."""
  378. expires = None
  379. if morsel['max-age']:
  380. try:
  381. expires = int(time.time() + int(morsel['max-age']))
  382. except ValueError:
  383. raise TypeError('max-age: %s must be integer' % morsel['max-age'])
  384. elif morsel['expires']:
  385. time_template = '%a, %d-%b-%Y %H:%M:%S GMT'
  386. expires = calendar.timegm(
  387. time.strptime(morsel['expires'], time_template)
  388. )
  389. return create_cookie(
  390. comment=morsel['comment'],
  391. comment_url=bool(morsel['comment']),
  392. discard=False,
  393. domain=morsel['domain'],
  394. expires=expires,
  395. name=morsel.key,
  396. path=morsel['path'],
  397. port=None,
  398. rest={'HttpOnly': morsel['httponly']},
  399. rfc2109=False,
  400. secure=bool(morsel['secure']),
  401. value=morsel.value,
  402. version=morsel['version'] or 0,
  403. )
  404. def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
  405. """Returns a CookieJar from a key/value dictionary.
  406. :param cookie_dict: Dict of key/values to insert into CookieJar.
  407. :param cookiejar: (optional) A cookiejar to add the cookies to.
  408. :param overwrite: (optional) If False, will not replace cookies
  409. already in the jar with new ones.
  410. """
  411. if cookiejar is None:
  412. cookiejar = RequestsCookieJar()
  413. if cookie_dict is not None:
  414. names_from_jar = [cookie.name for cookie in cookiejar]
  415. for name in cookie_dict:
  416. if overwrite or (name not in names_from_jar):
  417. cookiejar.set_cookie(create_cookie(name, cookie_dict[name]))
  418. return cookiejar
  419. def merge_cookies(cookiejar, cookies):
  420. """Add cookies to cookiejar and returns a merged CookieJar.
  421. :param cookiejar: CookieJar object to add the cookies to.
  422. :param cookies: Dictionary or CookieJar object to be added.
  423. """
  424. if not isinstance(cookiejar, cookielib.CookieJar):
  425. raise ValueError('You can only merge into CookieJar')
  426. if isinstance(cookies, dict):
  427. cookiejar = cookiejar_from_dict(
  428. cookies, cookiejar=cookiejar, overwrite=False)
  429. elif isinstance(cookies, cookielib.CookieJar):
  430. try:
  431. cookiejar.update(cookies)
  432. except AttributeError:
  433. for cookie_in_jar in cookies:
  434. cookiejar.set_cookie(cookie_in_jar)
  435. return cookiejar