The cookie jar offers methods for writing (set_cookie
, clear
), but there’s no high level way to reading any of it i.e. no get_cookie
.
Given a cookie jar jar
, if one wanted to read the cookies, they’d need to iterate over it:
for cookie in jar:
...
Getting a specific cookie only adds to that (assuming a cookie set with domain
, path
, name
):
for cookie in jar:
if cookie.name == name:
if cookie.domain == domain:
if cookie.path == path:
...
An alternative is to access the underlying dictionary:
jar._cookies[domain][path][name]
In my particular case, I need to check cookies in unit tests (that e.g. they’re set correctly etc). While I can (and do) read from ._cookies
, I’m always wary of accessing _
attributes - it feels like I’m doing something I shouldn’t. A very simple implementation would just officialize it:
def get_cookie(domain: str, path: str, name: str) -> Cookie:
return self._cookies[domain][path][name]
Things to consider:
- what to do when the desired cookie doesn’t exist; e.g.
KeyError
works for me; - whether
domain
andpath
should be optional; - …which could then lead to a situation when there are multiple cookies with the same name (but different domains, paths).
If this is of interest, I can open a PR etc.
GH issue: Add a `CookieJar.get_cookie` method · Issue #104019 · python/cpython · GitHub