Search code examples
pythonqueuepython-asynciopickleaiohttp

Saving cookies via pickle aiohttp


I'm rewriting the library asyncsteampy for the current version of Steam. But when I try to save the session to a pickle file, an error occurs

async def create_steam_session(username, password, steam_guard, pkl_name, api_key, proxies):
    steam_client = SteamClient(username, password, f'steam_guards/{steam_guard}', api_key=api_key)
    await steam_client.login()
    return steam_client

async def authorization(username, password, steam_guard, pkl_name, api_key):
    steam_client = await create_steam_session(username, password, steam_guard, pkl_name, api_key)
    await steam_client._session.connector.close()
    with open(f'async_pkl/{pkl_name}', 'wb') as f:
        pickle.dump(steam_client, f)

If I don't use await steam_client._session.connector.close()I get an error TypeError: cannot pickle 'weakref' object I used to just delete it 'weakref' object But then the following error appears TypeError: cannot pickle '_contextvars.Context' object But after await steam_client._session.connector.close() the following error appeared TypeError: cannot pickle '_queue.SimpleQueue' object

How to solve the error '_queue.SimpleQueue' object?


Solution

  • You're trying to pickle an entire client, not the cookies. This won't work as a client has open sockets and other things that could never be pickled.

    I don't know what that particular library exposes, but aiohttp.ClientSession has a .save() and .load() method for cookies: https://docs.aiohttp.org/en/stable/client_reference.html#aiohttp.CookieJar.save

    Note that these are not stable across minor releases of aiohttp, so cookies saved in 3.9 may not load in 3.10 without a conversion script.