Skip to content

Instantly share code, notes, and snippets.

@gazpachoking
Last active August 29, 2015 14:06
Show Gist options
  • Select an option

  • Save gazpachoking/ca4634542e3d6f62fe1e to your computer and use it in GitHub Desktop.

Select an option

Save gazpachoking/ca4634542e3d6f62fe1e to your computer and use it in GitHub Desktop.
Saves and loads cookies for a requests Session to a file
import os
from cookielib import LWPCookieJar
import requests
s = requests.Session()
s.cookies = LWPCookieJar('cookiejar')
if not os.path.exists('cookiejar'):
# Create a new cookies file and set our Session's cookies
print('setting cookies')
s.cookies.save()
r = s.get('http://httpbin.org/cookies/set?k1=v1&k2=v2')
else:
# Load saved cookies from the file and use them in a request
print('loading saved cookies')
s.cookies.load(ignore_discard=True)
r = s.get('http://httpbin.org/cookies')
print(r.text)
# Save the Session's cookies back to the file
s.cookies.save(ignore_discard=True)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment