From 0354fe7aa51f79822e2311667b4e98c168d98118 Mon Sep 17 00:00:00 2001 From: luoshuijs Date: Sat, 24 Jun 2023 19:30:54 +0800 Subject: [PATCH] :art: Improve the `Cookie` class to allow it to accept more types of parameters --- simnet/client/base.py | 2 -- simnet/client/cookies.py | 30 +++++++++++++++++++++++++++++- 2 files changed, 29 insertions(+), 3 deletions(-) diff --git a/simnet/client/base.py b/simnet/client/base.py index ce82db6..e72f152 100644 --- a/simnet/client/base.py +++ b/simnet/client/base.py @@ -8,7 +8,6 @@ from httpx import AsyncClient, TimeoutException, Response, HTTPError, Timeout from simnet.client.cookies import Cookies from simnet.client.headers import Headers from simnet.errors import TimedOut, NetworkError, BadRequest, raise_for_ret_code, NotSupported -from simnet.utils.cookies import parse_cookie from simnet.utils.ds import generate_dynamic_secret, DSType, hex_digest from simnet.utils.enum_ import Region, Game from simnet.utils.types import ( @@ -72,7 +71,6 @@ class BaseClient(AsyncContextManager["BaseClient"]): write=5.0, pool=1.0, ) - cookies = parse_cookie(cookies) if isinstance(cookies, str) else cookies cookies = Cookies(cookies) self.headers = Headers(headers) self.player_id = player_id diff --git a/simnet/client/cookies.py b/simnet/client/cookies.py index e8cadba..0be425d 100644 --- a/simnet/client/cookies.py +++ b/simnet/client/cookies.py @@ -1,12 +1,40 @@ +from http.cookiejar import CookieJar +from http.cookies import SimpleCookie from typing import Optional from httpx import Cookies as _Cookies +from simnet.utils.types import CookieTypes + __all__ = ("Cookies",) class Cookies(_Cookies): - """An extension of the `httpx.Cookies` class that includes additional functionality.""" + """A wrapper around `httpx.Cookies` that provides additional functionality.""" + + def __init__(self, cookies: Optional[CookieTypes] = None): # skipcq: PYL-W0231 + if cookies is None or isinstance(cookies, dict): + self.jar = CookieJar() + if isinstance(cookies, dict): + for key, value in cookies.items(): + if isinstance(value, str): + self.set(key, value) + else: + self.set(key, str(value)) + elif isinstance(cookies, list): + self.jar = CookieJar() + for key, value in cookies: + self.set(key, value) + elif isinstance(cookies, Cookies): + self.jar = CookieJar() + for cookie in cookies.jar: + self.jar.set_cookie(cookie) + elif isinstance(cookies, str): + cookie = SimpleCookie(cookies) + for key, value in cookie.items(): + self.set(key, value.value) + else: + self.jar = cookies COOKIE_USER_ID_NAMES = ("ltuid", "account_id", "stuid", "ltuid_v2", "account_id_v2")