Python Requests and Persistent Sessions

Python Requests and persistent sessions

You can easily create a persistent session using:

s = requests.Session()

After that, continue with your requests as you would:

s.post('https://localhost/login.py', login_data)
# logged in! cookies saved for future requests.
r2 = s.get('https://localhost/profile_data.json', ...)
# cookies sent automatically!
# do whatever, s will keep your cookies intact :)

For more about Sessions: https://requests.readthedocs.io/en/latest/user/advanced/#session-objects

How can you persist a single authenticated requests session in python?

I'd wire up a property like this:

class RestClient:
_session = None

@property
def session(self):
if self._session:
return self._session

auth = requests.auth.HTTPBasicAuth(USERNAME, PASSWORD)
response = requests.post(
f"https://{ settings.HOST }/rest/session", auth=auth
)

session = requests.Session()
session_id = response.json().get("value")
session.headers.update({"api-session-id": session_id})

self._session = session
return session

Now you can simply do client.session and it will be set up on the first access and reused thereafter.

EDIT: To persist this between RestClient instances, change references to self._session to RestClient._session.

Store python requests session in persistent storage

If you use the dill package, you should be able to pickle the session where pickle itself fails.

>>> import dill as pickle
>>> pickled = pickle.dumps(session)
>>> restored = pickle.loads(pickled)

Get dill here: https://github.com/uqfoundation/dill

Actually, dill also makes it easy to store your python session across restarts, so you
could pickle your entire python session like this:

>>> pickle.dump_session('session.pkl')

Then restart python, and pick up where you left off.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill as pickle
>>> pickle.load_session('session.pkl')
>>> restored
<requests.sessions.Session object at 0x10c012690>


Related Topics



Leave a reply



Submit