Saturday, October 29, 2011

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

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.

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To post to this group, send email to django-users@googlegroups.com.
To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

No comments:

Post a Comment