django为什么同时具有authenticate方法和login方法? [英] Why does django have both an authenticate method and a login method?

查看:52
本文介绍了django为什么同时具有authenticate方法和login方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读身份验证教程,作者正在使用 authenticate()方法对登录表单中的凭据数据进行身份验证.结果被分配给像这样的用户变量

I'm going through an authentication tutorial and the author is using the authenticate() method to authenticate the credentials data from a login form. The result is assigned to a user variable like so

user = authenticate(用户名=用户名,密码=密码)

下一个:用户使用 login(请求,用户)

但是为什么有2种不同的方法?认证凭证不是登录过程的一部分吗?那么,为什么该部分也不能由 login 函数处理呢?还是在某些情况下确实要使用 authenticate 而不是 login ?

But why the 2 different methods? Isn't authenticating credentials supposed to be part of the procedure of loggin in? So why isn't that part handled by the login function as well? Or are there scenario's where you do want to use authenticate but not login ?

此外,如果凭据不正确怎么办?用户会变成null还是会引发异常?

Also, what happens when the credentials are bad? Will user become null or will an exception be thrown?

谢谢

推荐答案

authenticate(..) [Django-doc] will verify credentials. It thus looks if the authentication backend has a user with the given credentials, and if so, return that User objects. Otherwise it will return None. But it will not log in that user. You can thus use that for sensitive methods, for example ask the password of a user that is already logged in, when that user plans to remove their account.

另一方面,登录(..) [Django-doc] 登录用户.它将与该用户创建会话,并设置正确的会话变量.请注意,凭据是必需的.例如,您可以使用它来授予管理员访问帐户的权限(模拟"),或在某些人之间共享虚拟帐户".登录用户本身并不需要 先进行身份验证.

login(..) [Django-doc] on the other hand, logs in a user. It will create a session with that user, and set the correct session variables. Note that no credentials are necessary for this. You can for example use that to give an administrator access to an account ("impersonate"), or to share a "virtual account" among certain people. Logging in a user does not per se requires to authenticate first.

虽然两者之间关系密切,而且人们经常看到一种模式,即首先对用户进行身份验证,然后再登录,但这不一定是这种情况.

While the two are thus much related, and one often sees a pattern where first a user is authenticated, and then logged in, that is not necessarily the case.

这篇关于django为什么同时具有authenticate方法和login方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆