python 從dict 轉成 class 型別

Posted in :

看到神奇的用法, 趕快分享給大家.

範例是從json 檔取得 dict, 目的是要把json 或 dict 內容轉成 cookie 型別,

先來看 cookie class:
https://github.com/ultrafunkamsterdam/nodriver/blob/main/nodriver/cdp/network.py

@dataclass
class Cookie:
    """
    Cookie object
    """

    #: Cookie name.
    name: str

    #: Cookie value.
    value: str

    #: Cookie domain.
    domain: str

    #: Cookie path.
    path: str

    #: Cookie size.
    size: int

    #: True if cookie is http-only.
    http_only: bool

    #: True if cookie is secure.
    secure: bool

    #: True in case of session cookie.
    session: bool

    #: Cookie Priority
    priority: CookiePriority

    #: True if cookie is SameParty.
    same_party: bool

    #: Cookie source scheme type.
    source_scheme: CookieSourceScheme

    #: Cookie source port. Valid values are {-1, [1, 65535]}, -1 indicates an unspecified port.
    #: An unspecified port value allows protocol clients to emulate legacy cookie scope for the port.
    #: This is a temporary ability and it will be removed in the future.
    source_port: int

    #: Cookie expiration date as the number of seconds since the UNIX epoch.
    expires: typing.Optional[float] = None

    #: Cookie SameSite type.
    same_site: typing.Optional[CookieSameSite] = None

    #: Cookie partition key. The site of the top-level URL the browser was visiting at the start
    #: of the request to the endpoint that set the cookie.
    partition_key: typing.Optional[str] = None

    #: True if cookie partition key is opaque.
    partition_key_opaque: typing.Optional[bool] = None

    def to_json(self) -> T_JSON_DICT:
        json: T_JSON_DICT = dict()
        json["name"] = self.name
        json["value"] = self.value
        json["domain"] = self.domain
        json["path"] = self.path
        json["size"] = self.size
        json["httpOnly"] = self.http_only
        json["secure"] = self.secure
        json["session"] = self.session
        json["priority"] = self.priority.to_json()
        json["sameParty"] = self.same_party
        json["sourceScheme"] = self.source_scheme.to_json()
        json["sourcePort"] = self.source_port
        if self.expires is not None:
            json["expires"] = self.expires
        if self.same_site is not None:
            json["sameSite"] = self.same_site.to_json()
        if self.partition_key is not None:
            json["partitionKey"] = self.partition_key
        if self.partition_key_opaque is not None:
            json["partitionKeyOpaque"] = self.partition_key_opaque
        return json

    @classmethod
    def from_json(cls, json: T_JSON_DICT) -> Cookie:
        return cls(
            name=str(json["name"]),
            value=str(json["value"]),
            domain=str(json["domain"]),
            path=str(json["path"]),
            size=int(json["size"]),
            http_only=bool(json["httpOnly"]),
            secure=bool(json["secure"]),
            session=bool(json["session"]),
            priority=CookiePriority.from_json(json["priority"]),
            same_party=bool(json["sameParty"]),
            source_scheme=CookieSourceScheme.from_json(json["sourceScheme"]),
            source_port=int(json["sourcePort"]),
            expires=(
                float(json["expires"])
                if json.get("expires", None) is not None
                else None
            ),
            same_site=(
                CookieSameSite.from_json(json["sameSite"])
                if json.get("sameSite", None) is not None
                else None
            ),
            partition_key=(
                str(json["partitionKey"])
                if json.get("partitionKey", None) is not None
                else None
            ),
            partition_key_opaque=(
                bool(json["partitionKeyOpaque"])
                if json.get("partitionKeyOpaque", None) is not None
                else None
            ),
        )

code 的呼叫點:
https://github.com/ultrafunkamsterdam/nodriver/blob/main/nodriver/cdp/storage.py

def get_cookies(
    browser_context_id: typing.Optional[browser.BrowserContextID] = None,
) -> typing.Generator[T_JSON_DICT, T_JSON_DICT, typing.List[network.Cookie]]:
    """
    Returns all browser cookies.

    :param browser_context_id: *(Optional)* Browser context to use when called on the browser endpoint.
    :returns: Array of cookie objects.
    """
    params: T_JSON_DICT = dict()
    if browser_context_id is not None:
        params["browserContextId"] = browser_context_id.to_json()
    cmd_dict: T_JSON_DICT = {
        "method": "Storage.getCookies",
        "params": params,
    }
    json = yield cmd_dict
    return [network.Cookie.from_json(i) for i in json["cookies"]]

好神奇, 一行指令, 就完成轉換!

code 的呼叫點:
https://github.com/ultrafunkamsterdam/nodriver/blob/main/nodriver/core/browser.py

cookies = await connection.send(cdp.storage.get_cookies())

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *