Skip to content

Commit

Permalink
Add __getitem__ to PickleableCookieJar
Browse files Browse the repository at this point in the history
  • Loading branch information
CastagnaIT committed Sep 20, 2023
1 parent 1f45752 commit df9cf16
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions resources/lib/utils/cookies.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,41 @@ def __setstate__(self, state):
if '_cookies_lock' not in self.__dict__:
self._cookies_lock = RLock()

def __getitem__(self, name):
"""Dict-like __getitem__() for compatibility with client code. Throws
exception if there are more than one cookie with name. In that case,
use the more explicit get() method instead.
.. warning:: operation is O(n), not O(1).
"""
return self._find_no_duplicates(name)

def _find_no_duplicates(self, name, domain=None, path=None):
"""Both ``__get_item__`` and ``get`` call this function: it's never
used elsewhere in Requests.
:param name: a string containing name of cookie
:param domain: (optional) string containing domain of cookie
:param path: (optional) string containing path of cookie
:raises KeyError: if cookie is not found
:raises CookieConflictError: if there are multiple cookies
that match name and optionally domain and path
:return: cookie.value
"""
to_return = None
for cookie in iter(self):
if cookie.name == name:
if domain is None or cookie.domain == domain:
if path is None or cookie.path == path:
if to_return is not None:
# if there are multiple cookies that meet passed in criteria
raise Exception(f"There are multiple cookies with name, {name!r}") # pylint: disable=broad-except
# we will eventually return this as long as no cookie conflict
to_return = cookie.value
if to_return:
return to_return
raise KeyError(f"name={name!r}, domain={domain!r}, path={path!r}")

def save(cookie_jar, log_output=True):
"""Save a cookie jar to file and in-memory storage"""
if log_output:
Expand Down

0 comments on commit df9cf16

Please sign in to comment.