我如何使此代码块更简单?

时间:2019-06-16 15:50:26

标签: python django-rest-framework coding-style serializer

我使用Django-rest-framework做一个小项目。 在下面提示最佳实践样式代码,这将使其更简单。

class LoginSerializer(serializers.Serializer):
    phone = serializers.CharField()
    password = serializers.CharField()

    def validate(self, data):
        phone = data.get("phone", "")
        password = data.get("password", "")
        # need simplify the structure below
        if phone and password:
            user = authenticate(phone=phone, password=password)
            if user:
                if user.is_active:
                    data['user'] = user
                else:
                    raise exceptions.ValidationError('User is deactivated.')
            else:
                raise exceptions.ValidationError(
                    'Unable to login with given credentials.')
        else:
            raise exceptions.ValidationError(
                'Must provide username and password both.')
        return data

0 个答案:

没有答案