AuthenticationMiddleware

AuthenticationMiddleware

我正在阅读Django的源代码,遇到了一个关于AuthenticationMiddleware的问题。
如文档所述,authenticationmiddleware
将用户属性(模型的一个实例)添加到每个传入的HttpRequest
但我不明白这是如何在User中完成的。如下面的代码所示,AuthenticationMiddleware.process_request()在这里只是将一个process_request分配给LazyUser(),这与request.__class__模型无关。而且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 middleware requires session middleware to be installed. Edit your MIDDLEWARE_CLASSES setting to insert 'django.contrib.sessions.middleware.SessionMiddleware'."
        request.__class__.user = LazyUser()
        return None

简言之,我想知道当LazyUser.__get__()钩子在处理AuthenticationMiddleware时,幕后究竟发生了什么?是吗?

最佳答案

LazyUser对象是一个Python descriptor,即一个可以指示如何通过其父类的实例访问其自身的对象。(那是一口)让我看看能不能帮你把它分解一下:

# Having a LazyUser means we don't have to get the actual User object
# for each request before it's actually accessed.
class LazyUser(object):
    # Define the __get__ operation for the descripted object.
    # According to the docs, "descr.__get__(self, obj, type=None) --> value".
    # We don't need the type (obj_type) for anything, so don't mind that.
    def __get__(self, request, obj_type=None):
        # This particular request doesn't have a cached user?
        if not hasattr(request, '_cached_user'):
            # Then let's go get it!
            from django.contrib.auth import get_user
            # And save it to that "hidden" field.
            request._cached_user = get_user(request)
        # Okay, now we have it, so return it.
        return request._cached_user

class AuthenticationMiddleware(object):
    # This is done for every request...
    def process_request(self, request):
        # Sanity checking.
        assert hasattr(request, 'session'), "blah blah blah."
        # Put the descriptor in the class's dictionary. It can thus be
        # accessed by the class's instances with `.user`,  and that'll
        # trigger the above __get__ method, eventually returning an User,
        # AnonymousUser, or what-have-you.
        # Come to think of it, this probably wouldn't have to be done
        # every time, but the performance gain of checking whether we already
        # have an User attribute would be negligible, or maybe even negative.
        request.__class__.user = LazyUser()
        # We didn't mess with the request enough to have to return a
        # response, so return None.
        return None

这有帮助吗:)

10-06 01:10