Last updated 2 years ago by Shrikant Sharat Kandula
pythonIf you haven’t checked out @kennethreitz’s excellent python-requests library yet, I suggest you go do that immediately. Go on, I’ll wait for you.
Had your candy? That is one of the most beatiful piece of python code I’ve read. And its an excellent library with a very humane API.
Recently, I have been using this library for a few of my company’s internal
projects and at a point I needed to serialize and save Session
objects for
later. That wasn’t as straightforward as I first thought it’d be, so I am
sharing my experience here.
First off, let’s make a simple http server which we are going to contact with python-requests. The server should be able to handle cookie based sessions and also have basic auth, as these things are handled by python-requests’ Session objects on the client side. I won’t discuss the code for the server here, you can get it from the gist.
Once you have the server running, now for the client, lets do requests!
```language-python import requests as req
URL_ROOT = 'http://localhost:5050'
def getloggedin_session(name): session = req.session(auth=('user', 'pass'))
login_response = session.post(URL_ROOT + '/login', data={'name': name})
login_response.raise_for_status()
return session
def getwhoami(session): response = session.get(URLROOT + '/whoami') response.raiseforstatus() return response.text ```
I defined two functions here. The get_logged_in_session
will create a new
session and login to the http server and return that session. Any subsequent
requests using this sesssion will be made as if you have logged in. That’s what
will be tested with the get_whoami
function, which will just return the
response from /whoami
.
Lets test this out. Make sure the server.py
is running and in another
terminal,
```language-python $ python -i client.py
s = getloggedinsession('sharat') getwhoami(s) u'You are sharat' get_whoami(req.session(auth=('user', 'pass'))) u'You are a guest' ```
Works perfectly. If we pass it the logged in session, it gives us the username
and if we pass it a new session, it gives us a guest
.
Now, lets assume we have two functions, serialize_session
and
deserialize_session
which do exactly what their names say. We can test them
out by running a small test.py, as
```language-python from client import getloggedinsession, getwhoami from serializer import deserializesession, serializesession
session = getloggedinsession('sharat') dsession = deserializesession(serialize_session(session))
assert getwhoami(session) == getwhoami(dsession) print 'Success' ```
and a dummy serializer.py
```language-python def serialize_session(session): return session
def deserialize_session(session): return session ```
And with that, of course, the test will not fail
$ python test.py
Success