要重置密码,用户应该转到包含令牌的链接:
example.com/password-change/?token=8125b6da86694a19b5d76f30a04c9db8
鉴于我有以下代码:
def _get_and_check_password_recovery_token(request, token_hex):
try:
token = tokens.get_token(token_hex)
except Token.DoesNotExist:
raise Http404
if token.is_expired():
token.delete()
messages.warning(request,
'Link you use for password recovery became obsolete. Please, request another one.')
return redirect(reverse('password_recovery') + '?email=%s' % token.user.email)
return token
def password_change(request):
if request.method == 'POST':
form = forms.PasswordChangeForm(request.POST)
if form.is_valid():
token_hex = form.cleaned_data.get('token')
new_password = form.cleaned_data['new_password']
if token_hex:
token_or_response = _get_and_check_password_recovery_token(request, token_hex)
if isinstance(token_or_response, Token):
user = token_or_response.user
else:
return token_or_response
else:
...
...
else:
token_hex = request.GET.get('token')
if token_hex:
token_or_response = _get_and_check_password_recovery_token(request, token_hex)
if isinstance(token_or_response, Token):
token_hex = token_or_response.hex
else:
return token_or_response
form = forms.PasswordChangeForm(initial={'token': token_hex})
else:
form = forms.PasswordChangeForm() # TODO Authenticated user changes his password.
return render_template(request, 'accounts/password_change.html', {'password_change_form': form})
如您所见,必须在密码更改表单呈现之前和用户提交之后检查令牌。所以我调用了_get_and_check_password_recovery_token(request, token_hex)
2 次方法。它返回响应对象(未找到令牌或不正确)或令牌。而且我对此感到不舒服——这是完全不同的对象。
你们有没有更好的方法来编写这段代码?返回逻辑上不同的对象是否适用于 Python?