序列化器中的格式验证错误

问题描述 投票:0回答:2

DjangoRestFramework 似乎可以通过多种方式处理错误。序列化器类中的 ValidationError 并不总是返回相同的 JSON。

当前响应包含 JSON 列表/对象字符串:

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

希望实现:

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

我意识到这个响应是默认功能的结果。但是,我已经重写了验证函数:

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

views.py:

if serializer.is_valid(raise_exception=True):

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

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

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

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

{"detail": "Account exists with email address."}
json django serialization django-rest-framework django-rest-auth
2个回答
0
投票

也许您应该尝试覆盖 json 渲染器类并连接一个自定义渲染器类,您可以在其中检查状态代码并

detail
键入响应数据,然后适当地重新格式化该值。

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


0
投票

您可以尝试在

custom_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:
       # If it is a Validation Error
       if response.status_code == 400:
          errors_dict = e.get_full_details()
          final_message = {}
          for key, value in errors_dict.items():
             final_message[key] = value[0].get('message', '')
          response.data['detail'] = final_message
          response.data['status_code'] = response.status_code


    return response

为我工作。唯一的区别是,我在自定义装饰器函数中捕获了此异常,并在序列化器函数中增量添加了装饰器。

© www.soinside.com 2019 - 2024. All rights reserved.