Skip to content

Instantly share code, notes, and snippets.

@rozza
Created May 12, 2011 07:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rozza/968114 to your computer and use it in GitHub Desktop.
Save rozza/968114 to your computer and use it in GitHub Desktop.
current_user proxy for flask example
from flask import session, g
current_user = LocalProxy(get_user) # Global access to the current user
def get_user():
"""
A proxy for the User model
Is used as a `LocalProxy` so is context local.
Uses the `g` object to cache the `User` instance which prevents
multiple `User` lookups as well as being thread safe.
"""
# Prevents circular import
from frontend.user.models import User, AnonymousUser
# Ensure has session
if 'user_id' not in session:
if hasattr(g, '_cached_user'):
del(g._cached_user)
return AnonymousUser()
# If not cached - look it up and cache it
if not hasattr(g, '_cached_user'):
try:
g._cached_user = User.objects.get(id=session['user_id'])
except: # Update to capture the correct error eg: except DoesNotExist
session.pop('user_id')
return AnonymousUser()
return g._cached_user
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment