项目中修改密码
修改密码功能,前端将老密码和新密码发到后端,后端校验,返回信息,我反序列化时这里使用了obj.is_valid(raise_exception=True)会将钩子中 raise ValidationError({...})抛出的异常返回,但是状态码是 400, 前端想要200,所以要重写 异常类,将默认的状态码改成 200 ok
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.authentication import SessionAuthentication
from seahub.api2.authentication import TokenAuthentication
from rest_framework.permissions import IsAuthenticated
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework import status
from seahub.api2.throttling import UserRateThrottle
from rest_framework.exceptions import APIException
# ValidationError 中默认的状态码是 400
# APIException中默认的是 500状态码
# 使raise抛出的异常状态码 为 200 ok
class ValidationErrorFailed(APIException):
status_code = status.HTTP_200_OK
def __init__(self, detail):
self.detail = detail
class PasswordSerializer(serializers.Serializer):
def __init__(self, **kwargs):
# 在序列化类中使用request
self.request = kwargs.get('context').get('request')
super(PasswordSerializer, self).__init__(**kwargs)
def validate(self, attrs):
logging.info(attrs)
old_password = self.request.data.get('old_password')
new_password1 = self.request.data.get('new_password1')
new_password2 = self.request.data.get('new_password2')
user = self.request.user
logging.info(user)
logging.info(old_password)
if not user.check_password(old_password):
logging.info(user.check_password(old_password))
# 如果是 raise ValidationError({...}) 那么抛出的异常是400
raise ValidationErrorFailed({
"status": [False],
"msg":["Your old password was entered incorrectly. Please enter it again."]
})
if new_password1 != new_password2:
raise ValidationErrorFailed({
"status": [False],
"msg": ["The two password fields didn't match."]
})
return attrs
def save(self):
user = self.request.user
user.set_password(self.request.data.get('new_password1'))
user.save()
if config.FORCE_PASSWORD_CHANGE:
UserOptions.objects.unset_force_passwd_change(self.request.user.username)
UserOptions.objects.set_latest_passwd_change_time(user.username)
class PwdChange(APIView):
authentication_classes = (TokenAuthentication, SessionAuthentication)
permission_classes = (IsAuthenticated,)
throttle_classes = (UserRateThrottle,)
def post(self,request,*args, **kwargs):
request_data = request.data
auth_ser = PasswordSerializer(data=request_data, context={'request':request})
logging.info(auth_ser)
if auth_ser.is_valid(raise_exception=True):
auth_ser.save()
return Response({
"status": [True],
"msg": ["The password modify successfully."]
})
return Response({'status':False})
改之前:
改之后: