验证并处理错误以将有意义的状态传递回客户端

时间:2019-07-25 15:41:02

标签: python django graphene-python graphene-django

我使用的是graphene-django而不是rest api(其余框架)。我正在进行用户注册。在其余框架中,验证是在序列化器部分完成的,但是当使用graphene时,如何验证和处理将有意义的状态传递给客户端的错误?

这是注册码

class Register(graphene.Mutation):
    class Arguments:
        email = graphene.String(required=True)
        password = graphene.String(required=True)
        password_repeat = graphene.String(required=True)

    user = graphene.Field(UserQuery)
    success = graphene.Boolean()
    errors = graphene.List(graphene.String)

    @staticmethod
    def mutate(self, info, email, password, password_repeat):
        if password == password_repeat:
            try:
                user = User.objects.create(email=email)
                user.set_password(password)
                user.is_active = False
                user.full_clean()
                user.save()
                return Register(success=True, user=user)
            except ValidationError as e:
                import pdb
                pdb.set_trace()
                return Register(success=False, errors=[e])
        return Register(success=False, errors=['password', 'password is not matching'])

一个示例可以验证是否存在使用电子邮件的用户

1 个答案:

答案 0 :(得分:1)

最简单的方法如下:

    @staticmethod
    def mutate(root, info, email, password, password_repeat):
        errors = []
        if password == password_repeat:
            errors.append('password_is_not_matching')

        if User.objects.filter(email=email).exists():
            errors.append('email_is_already_registred')

        if len(errors) == 0:
            try:
                user = User.objects.create(email=email)
                user.set_password(password)
                user.is_active = False
                user.full_clean()
                user.save()
                return Register(success=True, user=user)
            except ValidationError as e:
                import pdb
                pdb.set_trace()
                return Register(success=False, errors=[e])
        return Register(success=False, errors=errors)

但是,如果您进行大量此类检查,则可能会出现问题-代码变得更加复杂,并且更难弄清实际突变的作用。

有关更多信息,请阅读this article