Create a gist now

Instantly share code, notes, and snippets.

Code for my article on serializing session objects of python-requests library.
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import requests as req
URL_ROOT = 'http://localhost:5050'
def get_logged_in_session(name):
session = req.session(auth=('user', 'pass'))
login_response = + '/login', data={'name': name})
return session
def get_whoami(session):
response = session.get(URL_ROOT + '/whoami')
return response.text
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import json
import requests as req
def serialize_session(session):
attrs = ['headers', 'cookies', 'auth', 'timeout', 'proxies', 'hooks',
'params', 'config', 'verify']
session_data = {}
for attr in attrs:
session_data[attr] = getattr(session, attr)
return json.dumps(session_data)
def deserialize_session(data):
session_data = json.loads(data)
if 'auth' in session_data:
session_data['auth'] = tuple(session_data['auth'])
if 'cookies' in session_data:
session_data['cookies'] = dict((key.encode(), val) for key, val in
return req.session(**session_data)
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
from bottle import default_app, get, post, auth_basic, run, request, abort
from beaker.middleware import SessionMiddleware
app = default_app()
app = SessionMiddleware(app, {
'session.type': 'cookie',
'session.cookie_expire': True,
'': True,
'session.validate_key': 'arandomkeystring',
def auth_check(username, password):
return username == 'user' and password == 'pass'
def login():
if 'name' not in request.forms:
abort(400, 'I need you name, hitchhiker!')
session = request.environ['beaker.session']
session['user'] = request.forms['name']
return 'ok'
def whoami():
session = request.environ['beaker.session']
return 'You are ' + session.get('user', 'a guest')
run(app=app, host='', port=5050)
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
from client import get_logged_in_session, get_whoami
from serializer import deserialize_session, serialize_session
session = get_logged_in_session('sharat')
dsession = deserialize_session(serialize_session(session))
assert get_whoami(session) == get_whoami(dsession)
print 'Success'

Hello shara,
the @auth_basic won't execute correctly on Bottle v0.11.2, do you have an idea what's going wrong? I also want to keep on beaker for sessions management.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment