5Compatibility code to be able to use `cookielib.CookieJar` with requests.
7requests.utils imports from here, so be careful with imports.
14from ._internal_utils
import to_native_string
15from .compat
import Morsel, MutableMapping, cookielib, urlparse, urlunparse
20 import dummy_threading
as threading
24 """Wraps a `requests.Request` to mimic a `urllib2.Request`.
26 The code in `cookielib.CookieJar` expects this interface in order to correctly
27 manage cookie policies, i.e., determine whether a cookie can be set, given the
28 domains of the request and the cookie.
30 The original request object is read-only. The client is responsible for collecting
31 the new headers via `get_new_headers()` and interpreting them appropriately. You
32 probably want `get_cookie_header`, defined below.
38 self.
type = urlparse(self.
_r.url).scheme
44 return urlparse(self.
_r.url).netloc
55 host = to_native_string(self.
_r.headers[
"Host"], encoding=
"utf-8")
56 parsed = urlparse(self.
_r.url)
79 """cookielib has no legitimate use for this method; add it back if you find one."""
81 "Cookie headers should be added with add_unredirected_header()"
104 """Wraps a `httplib.HTTPMessage` to mimic a `urllib.addinfourl`.
106 ...what? Basically, expose the parsed HTTP headers from the server response
107 the way `cookielib` expects to see them.
111 """Make a MockResponse for `cookielib` to read.
113 :param headers: a httplib.HTTPMessage or analogous carrying the headers
124def extract_cookies_to_jar(jar, request, response):
125 """Extract the cookies from the response into a CookieJar.
127 :param jar: cookielib.CookieJar (not necessarily a RequestsCookieJar)
128 :param request: our own requests.Request object
129 :param response: urllib3.HTTPResponse object
140def get_cookie_header(jar, request):
142 Produce an appropriate Cookie header string to be sent with `request`, or None.
152 """Unsets a cookie by name, by default over all domains and paths.
154 Wraps CookieJar.clear(), is O(n).
157 for cookie
in cookiejar:
166 for domain, path, name
in clearables:
171 """There are two cookies that meet the criteria specified in the cookie jar.
172 Use .get and .set and include domain and path args in order to be more specific.
177 """Compatibility class; is a cookielib.CookieJar, but exposes a dict
180 This is the CookieJar we create by default for requests and sessions that
181 don't specify one, since some clients may expect response.cookies and
182 session.cookies to support dict operations.
184 Requests does not use the dict interface internally; it's just for
185 compatibility with external client code. All requests code should work
186 out of the box with externally provided instances of ``CookieJar``, e.g.
187 ``LWPCookieJar`` and ``FileCookieJar``.
189 Unlike a regular CookieJar, this class is pickleable.
191 .. warning:: dictionary operations that are normally O(1) may be O(n).
194 def get(self, name, default=None, domain=None, path=None):
195 """Dict-like get() that also supports optional domain and path args in
196 order to resolve naming collisions from using one cookie jar over
199 .. warning:: operation is O(n), not O(1).
206 def set(self, name, value, **kwargs):
207 """Dict-like set() that also supports optional domain and path args in
208 order to resolve naming collisions from using one cookie jar over
226 """Dict-like iterkeys() that returns an iterator of names of cookies
229 .. seealso:: itervalues() and iteritems().
231 for cookie
in iter(self):
235 """Dict-like keys() that returns a list of names of cookies from the
238 .. seealso:: values() and items().
242 def itervalues(self):
243 """Dict-like itervalues() that returns an iterator of values of cookies
246 .. seealso:: iterkeys() and iteritems().
248 for cookie
in iter(self):
252 """Dict-like values() that returns a list of values of cookies from the
255 .. seealso:: keys() and items().
260 """Dict-like iteritems() that returns an iterator of name-value tuples
263 .. seealso:: iterkeys() and itervalues().
265 for cookie
in iter(self):
269 """Dict-like items() that returns a list of name-value tuples from the
270 jar. Allows client-code to call ``dict(RequestsCookieJar)`` and get a
271 vanilla python dict of key value pairs.
273 .. seealso:: keys() and values().
278 """Utility method to list all the domains in the jar."""
280 for cookie
in iter(self):
286 """Utility method to list all the paths in the jar."""
288 for cookie
in iter(self):
294 """Returns True if there are multiple domains in the jar.
295 Returns False otherwise.
300 for cookie
in iter(self):
307 """Takes as an argument an optional domain and path and returns a plain
308 old Python dict of name-value pairs of cookies that meet the
314 for cookie
in iter(self):
324 except CookieConflictError:
328 """Dict-like __getitem__() for compatibility with client code. Throws
329 exception if there are more than one cookie with name. In that case,
330 use the more explicit get() method instead.
332 .. warning:: operation is O(n), not O(1).
337 """Dict-like __setitem__ for compatibility with client code. Throws
338 exception if there is already a cookie of that name in the jar. In that
339 case, use the more explicit set() method instead.
341 self.
set(name, value)
344 """Deletes a cookie given a name. Wraps ``cookielib.CookieJar``'s
345 ``remove_cookie_by_name()``.
359 """Updates this jar with cookies from another CookieJar or dict-like"""
366 def _find(self, name, domain=None, path=None):
367 """Requests uses this method internally to get cookie values.
369 If there are conflicting cookies, _find arbitrarily chooses one.
370 See _find_no_duplicates if you want an exception thrown if there are
373 :param name: a string containing name of cookie
374 :param domain: (optional) string containing domain of cookie
375 :param path: (optional) string containing path of cookie
376 :return: cookie.value
378 for cookie
in iter(self):
384 raise KeyError(f
"name={name!r}, domain={domain!r}, path={path!r}")
387 """Both ``__get_item__`` and ``get`` call this function: it's never
388 used elsewhere in Requests.
390 :param name: a string containing name of cookie
391 :param domain: (optional) string containing domain of cookie
392 :param path: (optional) string containing path of cookie
393 :raises KeyError: if cookie is not found
394 :raises CookieConflictError: if there are multiple cookies
395 that match name and optionally domain and path
396 :return: cookie.value
399 for cookie
in iter(self):
403 if toReturn
is not None:
406 f
"There are multiple cookies with name, {name!r}"
413 raise KeyError(f
"name={name!r}, domain={domain!r}, path={path!r}")
416 """Unlike a normal CookieJar, this class is pickleable."""
417 state = self.__dict__.copy()
423 """Unlike a normal CookieJar, this class is pickleable."""
424 self.__dict__.
update(state)
425 if "_cookies_lock" not in self.__dict__:
429 """Return a copy of this RequestsCookieJar."""
436 """Return the CookiePolicy instance used."""
440def _copy_cookie_jar(jar):
456 """Make a cookie from underspecified parameters.
458 By default, the pair of `name` and `value` will be set for the domain ''
459 and sent on every request (this is sometimes called a "supercookie").
473 "rest": {
"HttpOnly":
None},
477 badargs = set(kwargs) - set(result)
480 f
"create_cookie() got unexpected keyword arguments: {list(badargs)}"
484 result[
"port_specified"] = bool(result[
"port"])
485 result[
"domain_specified"] = bool(result[
"domain"])
486 result[
"domain_initial_dot"] = result[
"domain"].
startswith(
".")
487 result[
"path_specified"] = bool(result[
"path"])
493 """Convert a Morsel object into a Cookie containing the one k/v pair."""
496 if morsel[
"max-age"]:
498 expires = int(
time.time() + int(morsel[
"max-age"]))
500 raise TypeError(f
"max-age: {morsel['max-age']} must be integer")
501 elif morsel[
"expires"]:
502 time_template =
"%a, %d-%b-%Y %H:%M:%S GMT"
505 comment=morsel[
"comment"],
506 comment_url=bool(morsel[
"comment"]),
508 domain=morsel[
"domain"],
513 rest={
"HttpOnly": morsel[
"httponly"]},
515 secure=bool(morsel[
"secure"]),
517 version=morsel[
"version"]
or 0,
521def cookiejar_from_dict(cookie_dict, cookiejar=None, overwrite=True):
522 """Returns a CookieJar from a key/value dictionary.
524 :param cookie_dict: Dict of key/values to insert into CookieJar.
525 :param cookiejar: (optional) A cookiejar to add the cookies to.
526 :param overwrite: (optional) If False, will not replace cookies
527 already in the jar with new ones.
530 if cookiejar
is None:
533 if cookie_dict
is not None:
534 names_from_jar = [
cookie.name for cookie
in cookiejar]
535 for name
in cookie_dict:
536 if overwrite
or (name
not in names_from_jar):
542def merge_cookies(cookiejar, cookies):
543 """Add cookies to cookiejar and returns a merged CookieJar.
545 :param cookiejar: CookieJar object to add the cookies to.
546 :param cookies: Dictionary or CookieJar object to be added.
550 raise ValueError(
"You can only merge into CookieJar")
553 cookiejar = cookiejar_from_dict(cookies, cookiejar=cookiejar, overwrite=
False)
557 except AttributeError:
558 for cookie_in_jar
in cookies:
add_unredirected_header(self, name, value)
add_header(self, key, val)
get_origin_req_host(self)
get_header(self, name, default=None)
set(self, name, value, **kwargs)
set_cookie(self, cookie, *args, **kwargs)
get_dict(self, domain=None, path=None)
_find(self, name, domain=None, path=None)
__setitem__(self, name, value)
__setstate__(self, state)
_find_no_duplicates(self, name, domain=None, path=None)
create_cookie(name, value, **kwargs)
remove_cookie_by_name(cookiejar, name, domain=None, path=None)