在Django中:Django:爲什麼_Cached_user是請求的實例屬性,而LazyUser是請求的類屬性?
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
正如你可以看到_cached_user
是request
實例的屬性,而LazyUser()是類要求的屬性:
request.__class__.user = LazyUser()
爲什麼不同? LazyUser
基本上只是檢查是否存在_cached_user
,如果不存在,則查詢用戶的session
後端。在這種情況下,LazyUser
和_cached_user
不應該是實例request
的屬性嗎?