在 Django authenticate() 期间我应该如何处理不同的失败场景?

How should I handle different failure scenarios during Django authenticate()?

我正在 Django 1.7 中编写自定义身份验证后端,它可能会因以下两个原因之一而失败:凭据无效或某种内部错误,例如数据库问题。根据失败情况,我想向用户提供不同的错误消息。 IE "Username or password is incorrect" 用于无效凭据,以及类似 "An error occurred, please try again or contact support" 的东西。

由于 authenticate() 需要 return 用户模型,我不能只 return 错误,所以我想知道的是:最好的方法是什么将错误冒泡到调用 authenticate()?

的视图

我倾向于使用适当的错误消息从 authenticate() 中抛出异常,然后在视图中捕获该异常。我认为这是处理它的最佳方式,但是我离 Django 专家还很远,所以我很想听听社区的想法。

抛出异常是我最好的选择,还是有更好的方法将身份验证失败从 authenticate() 冒泡到视图?如果抛出异常是我的最佳选择,是否有符合要求的预定义 Django 异常,或者我应该自己制作?

在自定义方法中首先使用 try except 你可以捕获数据库错误

在自定义方法中,用户对象将具有 check_password 方法

>>> try:
     user = User.objects.get(email='lennon@thebeatles.com')

    except:
        print("error with connection")

然后使用check_password方法你会得到密码错误

    >>> user = User.objects.get(email='lennon@thebeatles.com')
    >>> user
    <User: john>
    >>> user.check_password('johnpassword')
    True
    >>> 

我最终在我的视图中使用了 try/except 块,其中包含表示相关失败的自定义错误。