gpt4 book ai didi

python - Django 的 AuthenticationMiddleware 有什么技巧

转载 作者:太空宇宙 更新时间:2023-11-03 13:44:50 27 4
gpt4 key购买 nike

我在阅读 Django 的源代码时遇到了关于 AuthenticationMiddleware 的问题。

正如文档所说的AuthenticationMiddleware

Adds the user attribute (a instance of User model) to every incoming HttpRequest

但我不明白这是如何在 AuthenticationMiddleware.process_request() 中完成的。如下代码所示,process_request这里只是给request.__class__分配了一个LazyUser(),与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 Hook 处理 HttpRequest 时,幕后到底发生了什么??

最佳答案

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

这有帮助吗? :)

关于python - Django 的 AuthenticationMiddleware 有什么技巧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22346178/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com