Skip to content

Save cookies to a file #1056

Description

@schrodienieur

Checklist

  • I searched the HTTPX documentation but couldn't find what I'm looking for.
  • I looked through similar issues on GitHub, but didn't find anything.
  • I looked up "How to do ... in HTTPX" on a search engine and didn't find any information.
  • I asked the community chat for help.

Question

I've been using this code in requests to save cookies to a file.
session = requests.Session()
json.dump(session.cookies.get_dict(), open(cookies.txt, 'w'))

and this code to open cookies file and set it to session cookies
cookies = requests.utils.cookiejar_from_dict(json.load(open('Cookies/cookies.txt', 'r')))
session.cookies.update(cookies)

How i do that in httpx? because httpx.Client.cookies doesn't have get_dict attribute.

Thank you.

Activity

  1. florimondmanca commented on Jul 10, 2020

    @florimondmanca
    Contributor

    Hi,

    Cookies instances are mappings (the docs say "a dict-like cookie store", and "standard mutable mapping interface"), so you can pass them to dict() to get a JSON-serializable dict object back. Similarly Client(cookies=…) accepts a dict, so you can pass the result of json.load() to it.

    Example:

    import json
    import httpx
    
    client = httpx.Client()
    r = client.get('https://www.google.com')
    
    # Save cookies...
    
    with open('cookies.json', 'w') as f:
        json.dump(dict(client.cookies), f)
    
    # Load cookies...
    
    with open('cookies.json') as f:
        cookies = json.load(f)
    
    client = httpx.Client(cookies=cookies)

    Hope this helps!

    Note that there seems to be some caveats to this "dump-and-load cookies" approach with some websites, see #895.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionFurther information is requested

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions