Saturday, October 29, 2011

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

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.

On Oct 29, 5:45 am, Kevin <kveron...@gmail.com> wrote:
> 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