Created
May 12, 2011 07:44
-
-
Save rozza/968114 to your computer and use it in GitHub Desktop.
current_user proxy for flask example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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