Pickling and caching the current request.user, good or bad idea?

87 views
Skip to first unread message

Kevin

unread,
Oct 29, 2011, 6:45:41 AM10/29/11
to Django users
In my attempts to lower database hits, I found that on most of my
pages, auth_user is hit every time. I had an idea about caching this
object in the current session. Is this a good idea, or will it cause
more problems than it helps? If so, what type of problems will I be
looking at?

My app rarely modifies the auth_user table, if at all. Here is a
quick middleware I wrote to go aloneside the current
AuthenticationMiddleware, and it works perfectly! Only 2 database
hits when viewing an account page. One hit to the session table, and
other hit to the table which holds various account settings.

class UserPickleMiddleware(object):
def process_request(self, request):
if 'cached_user' not in request.session:
from django.contrib.auth import get_user
request.session['cached_user'] = get_user(request)
request._cached_user = request.session['cached_user']
return None

I place this just before the standard AuthenticationMiddleware. I
will continue to run tests and see how it functions, if say the user
is added or removed from a group.

My sessions are stored in a database, which makes this interesting.
As it's only hitting the database once to grab both the session and
current user information.

Kevin

unread,
Oct 29, 2011, 7:23:09 AM10/29/11
to Django users
Okay, so the last one there had a hickup, users could not longer
login, once they have logged out. It kept the AnonymousUser cached...

Here is an update which works with logging back in:

class UserPickleMiddleware(object):
def process_request(self, request):
if 'cached_user' not in request.session:
from django.contrib.auth import get_user
user = get_user(request)
if isinstance(user, User):
request.session['cached_user'] = user
if 'cached_user' in request.session:
request._cached_user = request.session['cached_user']
return None

This one makes sure that the user instance is indeed a regular User
and not some Anonymous person before setting the cached data. The
code could be more optimized. I didn't use an Else, because it's
needs to set the request variables. I'd rather write an extra "if"
instead of copying the same line to set the request variable twice.
Reply all
Reply to author
Forward
0 new messages