Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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