Django Rest Framework 3.1.1基于验证错误设置状态成功和失败

时间:2015-07-02 14:27:34

标签: python django api rest django-rest-framework

我是django框架的新手。请帮助我,如何在rest框架中添加额外的状态参数,以显示基于验证的响应的成功和失败。我尝试过to_indernal_value函数,但我不知道响应中的热设置状态参数 我的序列化器

class UserSerializer(serializers.ModelSerializer):
    """
    Abstract User Model Serilization
    """
    customer=CustomerSerializer()
    client_id = serializers.SerializerMethodField()
    client_secret = serializers.SerializerMethodField()

    class Meta:
        model = User
        fields = ('id','username', 'password','email', 'first_name', 'last_name', 'customer', 'client_id', 'client_secret')
        write_only_fields = ('password',)
        depth=2
    def get_client_id(self, obj):
        user_id=User.objects.filter(username=obj).first()
        client=Application.objects.filter(user_id=user_id).first()
        if client is not None:
            return client.client_id
        else:
            return ""

    def get_client_secret(self, obj):
        user_id=User.objects.filter(username=obj).first()
        client=Application.objects.filter(user_id=user_id).first()
        if client is not None:
            return client.client_secret
        else:
            return ""

    def create(self, validated_data):

        profile_data = validated_data.pop('customer')
        user=User(email=validated_data['email'], username=validated_data['username'], first_name=validated_data['first_name'], last_name=validated_data['last_name'])
        user.set_password(validated_data['password'])
        user.save()
        # user = User.objects.create(**validated_data)
        users_group = Group.objects.get(name='Customers')
        user.groups = [users_group]
        Application.objects.create(user=user, client_type=Application.CLIENT_CONFIDENTIAL,
                                   authorization_grant_type=Application.GRANT_PASSWORD)
        Customer.objects.create(user=user, **profile_data)
        return user


    def update(self, instance, validated_data):
        profile_data = validated_data.pop('customer')
        instance.first_name = validated_data.get('first_name', instance.first_name)
        instance.last_name = validated_data.get('last_name', instance.last_name)
        instance.username =validated_data.get('username', instance.username)
        instance.email = validated_data.get('email', instance.email)
        instance.password=make_password(validated_data.get('password', instance.password),salt=None,hasher='unsalted_md5')
        instance.save()
        #Customer.objects.update(user=instance, **profile_data)
        Customer.objects.filter(user=instance).values().update(**profile_data)
        return instance

我正在使用通用视图

class CustomerCreate(generics.CreateAPIView):
    """
    Only POST method is allowed without Authentication Token
    """
    model = User
    serializer_class = UserSerializer
    permission_classes = (IsAuthenticatedOrCreate,)

验证时的预期响应

{
    "Status":0
    "username": [
        "This field may not be blank."
    ],
    "customer": {
        "email_id": [
            "This field may not be blank."
        ],
        "latitude": [
            "A valid number is required."
        ],
        "mobile_no": [
            "This field may not be blank."
        ],
        "longitude": [
            "A valid number is required."
        ]
    },
    "password": [
        "This field may not be blank."
    ]
}

On success status set as success
{
   status:1
   created record details
}

1 个答案:

答案 0 :(得分:0)

我同意罗斯罗杰斯的评论。最好使用HTTP状态代码。

如果必须这样做,您可以覆盖exception_handler。

my_view_utils.py

def exception_handler(exc):
    """
        fork from rest_framework.views.exception_handler
    """
    ERROR_INDICATOR = 'status';

    if isinstance(exc, exceptions.APIException):
        headers = {}
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc, exceptions.ValidationError):
            exc.status_code = 422  # 422 Unprocessable Entity
            data = {ERROR_INDICATOR: 422, 'error_detail': exc.detail}
        else:
            data = {
                ERROR_INDICATOR: getattr(exc, 'error_code', False) or exc.status_code,
                'error_detail': exc.detail
            }

        if isinstance(exc, (exceptions.NotAuthenticated,
                            exceptions.AuthenticationFailed)):
            # auth failed, response
            data.update({ERROR_INDICATOR: status.HTTP_401_UNAUTHORIZED})

        return Response(data, status=exc.status_code, headers=headers)

    elif isinstance(exc, Http404):
        data = {ERROR_INDICATOR: 404}
        return Response(data, status=status.HTTP_404_NOT_FOUND)

    elif isinstance(exc, PermissionDenied):
        data = {ERROR_INDICATOR: 403}
        return Response(data, status=status.HTTP_403_FORBIDDEN)

    # Note: Unhandled exceptions will raise a 500 error.
    return None

settings.py

REST_FRAMEWORK = {
    'EXCEPTION_HANDLER': 'my_view_utils.exception_handler',
}