首先看middleware的定义:
auth模块有两个middleware:AuthenticationMiddleware和SessionAuthenticationMiddleware。
AuthenticationMiddleware负责向request添加user属性
class AuthenticationMiddleware(object): def process_request(self, request): assert hasattr(request, 'session'), ( "The Django authentication middleware requires session middleware " "to be installed. Edit your MIDDLEWARE_CLASSES setting to insert " "'django.contrib.sessions.middleware.SessionMiddleware' before " "'django.contrib.auth.middleware.AuthenticationMiddleware'." ) request.user = SimpleLazyObject(lambda: get_user(request))
可以看见AuthenticationMiddleware首先检查是否由session属性,因为它需要session存储用户信息。
user属性的添加,被延迟到了get_user()函数里。SimpleLazyObject是一种延迟的技术。
在来看SessionAuthenticationMiddleware的定义:
它负责session验证
class SessionAuthenticationMiddleware(object): """ Middleware for invalidating a user's sessions that don't correspond to the user's current session authentication hash (generated based on the user's password for AbstractUser). """ def process_request(self, request): user = request.user if user and hasattr(user, 'get_session_auth_hash'): session_hash = request.session.get(auth.HASH_SESSION_KEY) session_hash_verified = session_hash and constant_time_compare( session_hash, user.get_session_auth_hash() ) if not session_hash_verified: auth.logout(request)
通过比较user的get_session_auth_hash方法,和session里面的auth.HASH_SESSION_KEY属性,判断用户的session是否正确。
至于request里面的user对象,由有什么属性,需要看看get_user()函数的定义。
def get_user(request): if not hasattr(request, '_cached_user'): request._cached_user = auth.get_user(request) return request._cached_user
显然get_user方法在request增加了_cached_user属性,用来作为缓存。
因为用户认证需要查询数据库,得到用户的信息,所以减少开销是有必要的。
注意,这种缓存只针对同一个request而言的,即在一个view中多次访问request.user属性。
每次http请求都是新的request。
再接着看auth.get_user()方法的定义,深入了解request.user这个对象:
def get_user(request): """ Returns the user model instance associated with the given request session. If no user is retrieved an instance of `AnonymousUser` is returned. """ from .models import AnonymousUser user = None try: user_id = request.session[SESSION_KEY] backend_path = request.session[BACKEND_SESSION_KEY] except KeyError: pass else: if backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) user = backend.get_user(user_id) return user or AnonymousUser()
新闻热点
疑难解答