在django-social-auth
中,在某些情况下后端将引发ValueError
(例如,当用户取消登录请求时,或者如果用户尝试与已经与另一个用户关联的帐户关联)。如果用户遇到这些情况之一,则会在您的网站上向他们显示500错误。
那么,什么是最好的捕捉这些方法?我希望能够在发生这种情况时(通过消息框架)显示有用的消息,但是我对执行此操作的最佳方法不知所措。
我正在考虑编写自己的 View (在单独的应用程序中),该 View 仅包装social_auth
的associate_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/