Skip to content

Instantly share code, notes, and snippets.

@rca
Created September 18, 2013 18:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rca/6613537 to your computer and use it in GitHub Desktop.
Save rca/6613537 to your computer and use it in GitHub Desktop.
Persist a requests session between uses.
#!/usr/bin/env python
import pickle
import requests
URL = 'http://foo.com'
# create a session object
session = requests.Session()
# configure the session (optional)
session.auth = ('user', 'pass')
print 'auth before pickle: {}'.format(session.auth)
# use the session to make requests
response = session.get(URL)
# drop the session into a pickle object
session_pickle = pickle.dumps(session)
##
# do what you need to do to persit it somewhere
# e.g. request.session['requests_session'] = session_pickle
##
# when you need to use it again, depickle the object
##
# do what you need to do to get it from storage
# e.g. session_pickle = request.session['requests_session']
##
session = pickle.loads(session_pickle)
print 'auth after pickle: {}'.format(session.auth)
response = session.get(URL)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment