Skip to content

Instantly share code, notes, and snippets.

@alex-laties
Created December 17, 2012 03:06
Show Gist options
  • Save alex-laties/4315544 to your computer and use it in GitHub Desktop.
Save alex-laties/4315544 to your computer and use it in GitHub Desktop.
Accessing django sessions via a WSGI Middleware. Can be used in any python web stack that conforms to the PEP 333 WSGI specification. This includes bottle.
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings' #not using env.put as that does not execute immediately
from django.conf import settings
SessionStore = __import__(settings.SESSION_ENGINE, fromlist=['']).SessionStore
class DjangoSessionWSGIMiddleware(object):
transform = false #doesn't transform output of anything above in the stack
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
if 'HTTP_COOKIE' in environ:
cookie = {s.split('=')[0].strip(): s.split('=')[1].strip() for s in environ['HTTP_COOKIE'].split(';')}
if 'sessionid' in cookie:
session = SessionStore(session_key=cookie['sessionid'])
if session.exists(cookie['sessionid']):
session.load()
user_id = session.get('_auth_user_id')
# From here, you can load your user's django object
# and attach it to the environ object
# for example:
from django.contrib.auth.models import User
environ['CURRENT_USER'] = User.objects.get(id=user_id)
return self.app(environ, start_response) #this MUST occur, otherwise nothing above this in the stack will execute
# bounce the user since they're not logged in.
# alternatively, give them a redirect to the django login page
start_response('401 Unauthorized', [('Content-type', 'text/plain')])
return 'Not logged in.'
from bottle import app, request, route, run
from djangosession import DjangoSessionWSGIMiddleware
app = DjangoSessionWSGIMiddleware(app())
@route('/', method='GET')
def hello():
# since our middleware attaches the django user to the environ object,
# we can access it through the bottle request object like so:
user = request.environ['CURRENT_USER']
return 'Hello from bottle, %s' % str(user)
if __name__ == '__main__':
run(host='127.0.0.1', app=app)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment