gpt4 book ai didi

python - Django ModelBackend.authenticate 如何工作?

转载 作者:行者123 更新时间:2023-12-01 03:52:52 25 4
gpt4 key购买 nike

我正在调查ModelBackend

def authenticate(self, username=None, password=None, **kwargs):
UserModel = get_user_model()
if username is None:
username = kwargs.get(UserModel.USERNAME_FIELD)
try:
user = UserModel._default_manager.get_by_natural_key(username)
except UserModel.DoesNotExist:
# Run the default password hasher once to reduce the timing
# difference between an existing and a non-existing user (#20760).
UserModel().set_password(password)
else:
if user.check_password(password) and self.user_can_authenticate(user):
return user

我很困惑。

  1. 在哪里调用authenticate()
  2. 什么是将用户名密码传递给authenticate()

有时,代码可以工作,但我不知道它是如何工作的。

更新

我正在阅读一个项目的源代码。我找到了authenticate()的定义,但找不到它的调用位置。

grep -r "authenticate" .

./src/myproject/views.py: if request.user.is_authenticated():
./src/lib/backend.py: def authenticate(self, username = None, password = None, **kwargs):
./src/lib/middleware.py: if not request.user.is_authenticated():
./src/lib/decorators.py: if request.user.is_authenticated():

最佳答案

authenticate() 本身无法“工作”。

如果您的项目或应用程序实现了登录表单,那么您或用于身份验证的应用程序的开发人员将调用 authenticate()

例如,如果您有一个包含用户名密码字段的登录表单,那么您可以调用authenticate(username, password)在您的 post() 方法中。

例如;

if request.method == 'POST':
# Gather the username and password provided by the user.
# This information is obtained from the login form.
username = request.POST['username']
password = request.POST['password']

# Use Django's machinery to attempt to see if the username/password
# combination is valid - a User object is returned if it is.
user = authenticate(username=username, password=password)
# If we have a User object, the details are correct.
# If None (Python's way of representing the absence of a value), no user
# with matching credentials was found.
if user:
# Is the account active? It could have been disabled.
if user.is_active:
# If the account is valid and active, we can log the user in.
# We'll send the user back to the homepage.
login(request, user)
return HttpResponseRedirect('/rango/')
else:
# An inactive account was used - no logging in!
return HttpResponse("Your Rango account is disabled.")
else:
# Bad login details were provided. So we can't log the user in.
print "Invalid login details: {0}, {1}".format(username, password)
return HttpResponse("Invalid login details supplied.")

参见here有关此代码的完整编写,或查看官方 django docsauthenticate()上。

关于python - Django ModelBackend.authenticate 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37954187/

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