Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
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

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