2

我正在使用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'])

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

4

1 回答 1

2

最简单的方法如下所示:

    @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)

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

欲了解更多信息,请阅读这篇文章

于 2019-07-25T16:17:47.430 回答