from rest_framework import status from rest_framework.views import APIView from rest_framework.permissions import IsAuthenticated from utils.response_codes import ( ResponseCode, create_standardized_response, create_standardized_error_response ) from ..serializers.user_serializers import ( SendPhoneCodeSerializer, ChangePhoneSerializer, UserSerializer, ) class SendPhoneCodeAPIView(APIView): permission_classes = [IsAuthenticated] def post(self, request): serializer = SendPhoneCodeSerializer( data=request.data, context={'request': request} ) if not serializer.is_valid(): errors = serializer.errors first_error = '' for field, msgs in errors.items(): if isinstance(msgs, list) and msgs: first_error = str(msgs[0]) break return create_standardized_error_response( data=errors, code=ResponseCode.PARAMETER_ERROR, message=first_error or '参数异常', status_code=status.HTTP_400_BAD_REQUEST ) try: phone = serializer.save() return create_standardized_response( data={'phone_sent': True}, code=ResponseCode.SUCCESS, status_code=status.HTTP_200_OK ) except Exception as e: return create_standardized_error_response( message=f'验证码发送失败: {str(e)}', code=ResponseCode.SERVER_INTERNAL_ERROR, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR ) class ChangePhoneAPIView(APIView): permission_classes = [IsAuthenticated] def post(self, request): serializer = ChangePhoneSerializer( data=request.data, context={'request': request} ) if not serializer.is_valid(): errors = serializer.errors first_error = '' for field, msgs in errors.items(): if isinstance(msgs, list) and msgs: first_error = str(msgs[0]) break return create_standardized_error_response( data=errors, code=ResponseCode.PARAMETER_ERROR, message=first_error or '参数异常', status_code=status.HTTP_400_BAD_REQUEST ) try: updated_user = serializer.save() user_serializer = UserSerializer(updated_user) return create_standardized_response( data={'user': user_serializer.data}, code=ResponseCode.SUCCESS, status_code=status.HTTP_200_OK ) except Exception as e: return create_standardized_error_response( message=f'手机号修改失败: {str(e)}', code=ResponseCode.SERVER_INTERNAL_ERROR, status_code=status.HTTP_500_INTERNAL_SERVER_ERROR )