5

DjangoRestFramework 似乎以多种方式处理错误。序列化程序类中的 ValidationError 不会始终返回相同的 JSON。

当前响应包括一个 JSON 列表/对象字符串:

{"detail":["Unable to log in with provided credentials."]}

期待实现:

{"detail":"Unable to log in with provided credentials."}

我意识到这个响应是默认函数的结果。但是,我已经覆盖了 validate 函数:

class AuthCustomTokenSerializer(serializers.Serializer):
username = serializers.CharField(write_only=True)
password = serializers.CharField(write_only=True)
token = serializers.CharField(read_only=True)

def validate(self, validated_data):
    username = validated_data.get('username')
    password = validated_data.get('password')

    # raise serializers.ValidationError({'detail': 'Unable to log in with provided credentials.'})

    if username and password:
        user = authenticate(phone_number=username, password=password)

        try:

            if UserInfo.objects.get(phone_number=username):
                userinfo = UserInfo.objects.get(phone_number=username)
                user = User.objects.filter(user=userinfo.user, password=password).latest('date_joined')

            if user:

                if user.is_active:
                    validated_data['user'] = user
                    return validated_data

                else:
                    raise serializers.ValidationError({"detail": "User account disabled."})

        except UserInfo.DoesNotExist:
            try:
                user = User.objects.filter(email=username, password=password).latest('date_joined')

                if user.is_active:
                    validated_data['user'] = user
                    return validated_data

            except User.DoesNotExist:
                #raise serializers.ValidationError("s")
                raise serializers.ValidationError({'detail': 'Unable to log in with provided credentials.'})
    else:
        raise serializers.ValidationError({"detail" : "Must include username and password."})

class Meta:
    model = Token
    fields = ("username", "password", "token")

我尝试添加自定义异常处理程序:

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code


    return response

视图.py:if serializer.is_valid(raise_exception=True):

但是,这只会附加当前引发的错误:

{"detail":["Unable to log in with provided credentials."],"status_code":400}

我应该如何使用更改返回文本的格式?它只在 validate 函数中为这个特定的序列化程序返回这样的 JSON。

我还研究了格式化 non_field_errors 模板,但它适用于我的所有其他序列化程序,例如:

{"detail": "Account exists with email address."}
4

1 回答 1

0

也许您应该尝试覆盖 json 渲染器类并连接一个自定义渲染器类,您可以在其中检查状态代码并detail键入响应数据,然后适当地重新格式化该值。

我从来没有尝试过,所以我不能给你确切的代码库,但这是我能想到的唯一能得到一致响应的方法。

于 2016-02-22T20:57:13.453 回答