python - 验证和登录之间有什么区别?

标签 python django django-authentication django-1.7

文档:https://docs.djangoproject.com/en/1.7/topics/auth/default/#django.contrib.auth.login

When you’re manually logging a user in, you must call authenticate() before you call login(). authenticate() sets an attribute on the User noting which authentication backend successfully authenticated that user (see the backends documentation for details), and this information is needed later during the login process. An error will be raised if you try to login a user object retrieved from the database directly.

那么为什么 authenticatelogin 是两个独立的函数呢?据我了解,authenticate 只是验证登录信息。 login 将获取用户对象并设置 cookie。我认为它们是分开的唯一原因是因为也许您可以放入不同的用户对象,比如用户合并了 2 个帐户。也许您想先验证电子邮件地址。这就是为什么它们是独立的函数并且 login 不包装 authenticate 的原因吗?

最佳答案

这是单一职责原则的问题:一个方法应该做一件合乎逻辑的事情。正如您自己指出的,这两个步骤在逻辑上是不同的:

authenticate just verifies the login information. login will take the user object and set the cookies

进一步说明,身份验证是一次性检查, 并不意味着登录 session 。 登录 session 意味着用户可以在一段时间内自由执行各种受限事件而无需重复身份验证检查。

有时您可能需要在不登录的情况下对用户进行身份验证(验证他们的真实身份)。 如果这两个功能合而为一, 你不能那样做, 即使你只是想做一次一次性检查, 你必须让他们登录,创建一个 session , 这是没有意义的。 由于这些目的明显不同, 有两种方法非常有意义。

分离也使测试更容易。如果您编写一个新的身份验证后端,您可能希望能够单独测试身份验证步骤是否有效,而不必担心整个登录系统如何工作,这不是您的后端的责任。

将方法分解为逻辑上独立的最小元素是明智之举,有很多好处。

关于python - 验证和登录之间有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28249276/

相关文章:

python - 使用数据帧求解系数的二次方程

python - 如何在不覆盖旧数据的情况下在另一个字典中创建字典

python - urls.py 和重定向 url

python - 通过 Pydev 使用 Django 时出现间歇性 "Page Not Found"

django 1.5 扩展默认用户模型或替换它

python - 使用 python 根据公共(public)字段合并 2 个 csv 文件

python - 导入错误: No module named youtube_dl

python - 在迁移到 Django 1.6 时摆脱 get_profile()

带有 "no such table: app_customuser"的 django 错误的 python-social-auth

DJANGO:TemplateDoesNotExist:auth/user_confirm_delete.html