我正在开发一个验证模块,从“django.contrib.auth”中获取灵感并取而代之。
他们正在做什么以及为什么?
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
request.__class__.user
而不仅仅是request.user
?我会添加身份验证,登录和注销例程,但不想让你厌烦太多的代码转储。我想我现在明白了,(最后一个问题可能是关键)但只是强迫自己(在某种程度上)明智地提出问题: - )
答案 0 :(得分:4)
request
的类属性(与实例属性相对),这使其可以作为descriptor正常工作。