I am making a series of API calls using Python similar to the following:
response = requests.post('https://httpbin.org/post', data = {'key':'value'})
When my API call is successful, I am able to view the cookies using response.cookies giving me the cookies in the following type: requests.cookies.RequestsCookieJar.
I then want to store these cookies in MacOS Keychain so that I can use them later. I am doing this with keyring similar to the following:
keyring.set_password("test", "test", cookies)
Although KeyChain requires the storage type to be text (UTF-8 encoding). How can I serialize the cookies so they can be stored? And how can I repackage the cookies for a future request after retrieving them as text?
To store the cookies, it might be as simple as using cookies = json.dumps(dict(cookies)) to convert the RequestsCookieJar to a dictionary and then a string (readable as JSON). That will likely satisfy the keyring storage type requirement.
Likewise, to convert this json string back to a dictionary for a future request, you can load the cookies like this: cookies = json.loads(cookies)
How can I serialize a Python request's cookies for UTF-8 storage?