python - 如何在 Python 中验证 GraphQL 突变

标签 python graphql

我是 GraphQL 新手。我正在使用Graphene-Django并有一个名为 CreateUser 的突变。它需要三个参数用户名电子邮件密码

如何验证数据并返回多个错误?

我想要返回这样的东西。

{  
   "name":[  
      "Ensure this field has at least 2 characters."
   ],
   "email":[  
      "This field may not be blank."
   ],
   "password":[  
      "This field may not be blank."
   ]
}

所以我可以像这样在表单上呈现错误:

enter image description here

到目前为止我的代码:

from django.contrib.auth.models import User as UserModel
from graphene_django import DjangoObjectType
import graphene


class User(DjangoObjectType):
    class Meta:
        model = UserModel
        only_fields = 'id', 'username', 'email'


class Query(graphene.ObjectType):
    users = graphene.List(User)
    user = graphene.Field(User, id=graphene.Int())

    def resolve_users(self, info):
        return UserModel.objects.all()

    def resolve_user(self, info, **kwargs):
        try:
            return UserModel.objects.get(id=kwargs['id'])
        except (UserModel.DoesNotExist, KeyError):
            return None


class CreateUser(graphene.Mutation):

    class Arguments:
        username = graphene.String()
        email = graphene.String()
        password = graphene.String()

    user = graphene.Field(User)

    def mutate(self, info, username, email, password):
        user = UserModel.objects.create_user(username=username, email=email, password=password)
        return CreateUser(user=user)


class Mutation(graphene.ObjectType):
    create_user = CreateUser.Field()


schema = graphene.Schema(query=Query, mutation=Mutation)

最佳答案

主要通过使用联合来对架构中的错误进行建模。

SDL 格式:

type RegisterUserSuccess {
  user: User!
}

type FieldError {
  fieldName: String!
  errors: [String!]!
}

type RegisterUserError {
  fieldErrors: [FieldError!]!
  nonFieldErrors: [String!]!
}


union RegisterUserPayload = RegisterUserSuccess | RegisterUserError

mutation {
  registerUser(name: String, email: String, password: String): RegisterUserPayload!
}

关于python - 如何在 Python 中验证 GraphQL 突变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49283044/

相关文章:

reactjs - React-Select 与 React-Apollo 不起作用

node.js - GraphQL 查询在 node-georedis API 回调完成之前返回数据(异步问题?)

python - Docker没有在KeyboardInterrupt上保存文件

graphql - 错误消息: Instance Data is not valid whilst updating a GraphQL schema

python - 等待文件的脚本在 while 循环中使用 100% CPU

python - 计算随机发生的麻烦

types - 在 GraphQL 类型定义中创建条件属性

kotlin - Page 类的 graphql 架构定义应该是什么样子?

python - pyPdf 错误参数无效

python - 如何将从 Firebase 导出的数据作为 json 加载到 Python 脚本中