django - 如何处理django-social-auth引发的异常?

标签 django authentication social django-socialauth

django-social-auth中,在某些情况下后端将引发ValueError(例如,当用户取消登录请求时,或者如果用户尝试与已经与另一个用户关联的帐户关联)。如果用户遇到这些情况之一,则会在您的网站上向他们显示500错误。

那么,什么是最好的捕捉这些方法?我希望能够在发生这种情况时(通过消息框架)显示有用的消息,但是我对执行此操作的最佳方法不知所措。

我正在考虑编写自己的 View (在单独的应用程序中),该 View 仅包装social_authassociate_complete View ,但这似乎很笨拙……有什么想法吗?

我可以 fork django-social-auth并自定义此行为,但我不希望保留单独的 fork -尤其是因为我无法假设所有人都希望以相同的方式处理这些Exception。

最佳答案

我遇到了同样的问题,看来,创建包装 View 是目前处理这种情况的最佳方法。这是我的工作方式:

def social_auth_login(request, backend):
    """
        This view is a wrapper to social_auths auth
        It is required, because social_auth just throws ValueError and gets user to 500 error
        after every unexpected action. This view handles exceptions in human friendly way.
        See https://convore.com/django-social-auth/best-way-to-handle-exceptions/
    """
    from social_auth.views import auth

    try:
        # if everything is ok, then original view gets returned, no problem
        return auth(request, backend)
    except ValueError, error:
        # in case of errors, let's show a special page that will explain what happened
        return render_to_response('users/login_error.html',
                                  locals(),
                                  context_instance=RequestContext(request))

您将必须为其设置url:
urlpatterns = patterns('',
    # ...
    url(r'^social_auth_login/([a-z]+)$',  social_auth_login, name='users-social-auth-login'), 
)

然后像以前一样在模板中使用它:
<a href="{% url 'users-social-auth-login' "google" %}">Log in with Google</a>

希望这对您有所帮助,即使在问了问题两个月之后:)

关于django - 如何处理django-social-auth引发的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6463320/

相关文章:

python - Django allauth 访问 View

ios - 构建到iOS时Unity C#Social.LoadUsers导致一致的崩溃

cakephp - 什么是 CakePHP 最好的开源/免费 "social network integration"插件/库

asp.net-mvc - 为什么在login action中添加claim后,在其他controller中无法访问?

c# - 在 Blazor 应用程序中使用 Azure Active Directory 时如何在 asp net core 3.1 中自定义注销页面

python - 如何在pymongo连接中的密码中转义@?

open-source - 为各种项目寻找开源程序员?

django-nose:无法使用 --failed 查看自定义用户模型

javascript - 为什么Django翻译不使用javascript中的基础语言?

django - 在 Django 中注册后重定向到上一页