Skip to content

Instantly share code, notes, and snippets.

@sharat87
Created May 11, 2012 17:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sharat87/2660997 to your computer and use it in GitHub Desktop.
Save sharat87/2660997 to your computer and use it in GitHub Desktop.
Code for my article on serializing session objects of python-requests library. http://sharats.me/serializing-python-requests-session-objects-for-fun-and-profit.html
#!/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 = session.post(URL_ROOT + '/login', data={'name': name})
login_response.raise_for_status()
return session
def get_whoami(session):
response = session.get(URL_ROOT + '/whoami')
response.raise_for_status()
return response.text
bottle
beaker
requests
#!/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
session_data['cookies'].items())
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,
'session.auto': True,
'session.validate_key': 'arandomkeystring',
})
def auth_check(username, password):
return username == 'user' and password == 'pass'
@post('/login')
@auth_basic(check=auth_check)
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'
@get('/whoami')
@auth_basic(check=auth_check)
def whoami():
session = request.environ['beaker.session']
return 'You are ' + session.get('user', 'a guest')
run(app=app, host='127.0.0.1', 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'
@yedderson
Copy link

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