Django的AuthenticationMiddleware有什么诀窍

时间:2014-03-12 08:46:22

标签: python django

我正在阅读Django的源代码并遇到有关AuthenticationMiddleware的问题。

正如文档中所说的AuthenticationMiddleware

  

将用户属性(User模型的实例)添加到每个传入的HttpRequest

但我无法理解AuthenticationMiddleware.process_request()如何做到这一点。如下面的代码所示,此处process_request只是将LazyUser()分配给request.__class__,这与User模型无关。 LazyUser.__get__()似乎很奇怪,让我很困惑。

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

简单地说,我想知道当AuthenticationMiddleware挂钩处理HttpRequest ??

时,幕后发生了什么

2 个答案:

答案 0 :(得分:6)

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

这有帮助吗? :)

答案 1 :(得分:0)

LazyUser只是一个包装器,一个懒惰的包装器。 get 方法是Python的魔术方法之一,当访问die对象时将调用它。因此,仅在用户实际使用时确定用户。这是有道理的,因为此操作将触发数据库调用,并且只有在真正需要用户时才会发生这种情况。

LazyUser不是分配给请求实例本身,而是分配给reqeust的实例类,它也使实例可用。为什么这样做是我无法分辨的。