开发者

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 simply request.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 :-)


  1. No. It pulls the user at most once per request, but does not span requests.
  2. Yes.
  3. They do. The store the PK.
  4. So that it becomes a class attribute of request (as opposed to an instance attribute), which allows it to work correctly as a descriptor.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜