Can you explain how "django.contrib.auth" works to me please?
I'm working on an authentication module drawing inspiration from and replacing "django.contrib.auth".
What are they doing with all this and why?
def get_user(request):
from django.contrib.auth.models import AnonymousUser
try:
user_id = request.session[SESSION_KEY]
backend_path = request.session[BACKEND_SESSION_KEY]
backend = load_backend(backend_path)
user = backend.get_user(user_id) or AnonymousUser()
except KeyError:
user = AnonymousUser()
return user
class LazyUser(object):
def __get__(self, request, obj_type=None):
if not hasattr(request, '_cached_user'):
from django.contrib.auth import get_user
request._cached_user = get_user(request)
return request._cached_user
class AuthenticationMiddleware(object):
def process_request(self, request):
assert hasattr(request, 'session'), "The Django authentication ..."
request.__class__.user = LazyUser()
return None
- Is it trying to prevent a database hit for the user instance on every request?
- Does it go stale if the user record is altered?
- Why don't they simply save the user instance, or a key to it, in the session?
- why assign to
request.__class__.user
and not simplyrequest.user
?
I'd add the authenticate, login, and logout routines but don't wa开发者_StackOverflownt to bore you with too many code dumps. I think I get it now, (that last question might be the key) but only by having forced myself to lay out the question (somewhat) sensibly :-)
- No. It pulls the user at most once per request, but does not span requests.
- Yes.
- They do. The store the PK.
- So that it becomes a class attribute of
request
(as opposed to an instance attribute), which allows it to work correctly as a descriptor.
精彩评论