Skip to content

Commit

Permalink
Make Session.cookies a property (#446)
Browse files Browse the repository at this point in the history
This allows users to replace session.cookies after initialization with any CookieTypes object.
This behavior matches httpx and requests, and allows it to be a drop-in replacement even in less typical usecases.

httpx uses property in the same manner:
https://github.com/encode/httpx/blob/47f4a96/httpx/_client.py#L317-L326

requests appears to differ at first glance, as it does not use a property,
but each request calls merge_cookies, which converts dicts to cookie jars, so it's virtually identical
https://github.com/psf/requests/blob/23540c9/src/requests/sessions.py#L241
https://github.com/psf/requests/blob/23540c9/src/requests/cookies.py#L552-L553
  • Loading branch information
Velocidensity authored Dec 1, 2024
1 parent f6eea01 commit 4193027
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions curl_cffi/requests/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ def __init__(
response_class: Optional[Type[Response]] = None,
):
self.headers = Headers(headers)
self.cookies = Cookies(cookies)
self._cookies = Cookies(cookies)
self.auth = auth
self.base_url = base_url
self.params = params
Expand Down Expand Up @@ -551,7 +551,7 @@ def _set_curl_options(
c.setopt(CurlOpt.COOKIEFILE, b"") # always enable the curl cookie engine first
c.setopt(CurlOpt.COOKIELIST, "ALL") # remove all the old cookies first.

for morsel in self.cookies.get_cookies_for_curl(req):
for morsel in self._cookies.get_cookies_for_curl(req):
# print("Setting", morsel.to_curl_format())
curl.setopt(CurlOpt.COOKIELIST, morsel.to_curl_format())
if cookies:
Expand Down Expand Up @@ -813,9 +813,9 @@ def _parse_response(self, curl, buffer, header_buffer, default_encoding):
morsels = [CurlMorsel.from_curl_format(c) for c in c.getinfo(CurlInfo.COOKIELIST)]
# for l in c.getinfo(CurlInfo.COOKIELIST):
# print("Curl Cookies", l.decode())
self.cookies.update_cookies_from_curl(morsels)
rsp.cookies = self.cookies
# print("Cookies after extraction", self.cookies)
self._cookies.update_cookies_from_curl(morsels)
rsp.cookies = self._cookies
# print("Cookies after extraction", self._cookies)
rsp.primary_ip = cast(bytes, c.getinfo(CurlInfo.PRIMARY_IP)).decode()
rsp.local_ip = cast(bytes, c.getinfo(CurlInfo.LOCAL_IP)).decode()
rsp.default_encoding = default_encoding
Expand All @@ -832,6 +832,14 @@ def _check_session_closed(self):
if self._closed:
raise SessionClosed("Session is closed, cannot send request.")

@property
def cookies(self) -> Cookies:
return self._cookies

@cookies.setter
def cookies(self, cookies: CookieTypes) -> None:
self._cookies = Cookies(cookies)


class Session(BaseSession):
"""A request session, cookies and connections will be reused. This object is thread-safe,
Expand Down

0 comments on commit 4193027

Please sign in to comment.