GraphQL graphene-django基本使用ドキュメント


graphene-django基本使用ドキュメント
紹介する
API用のクエリー言語GraphQLは、API用のクエリー言語であり、データクエリーの実行時を満たす言語でもあります.GraphQLは、あなたのAPIのデータに対して理解しやすい完全な説明を提供し、クライアントが必要なデータを正確に取得することができ、冗長性がなく、APIを時間が経つにつれて進化させやすくし、強力な開発者ツールの構築にも使用できます.
ドキュメント
公式サイトhttp://graphql.cn/
リファレンスドキュメントhttps://passwo.gitbook.io/graphql/index/drf
個人プロジェクトの応用
https://github.com/hequan2017/seal
モジュール
pip install  graphene-django

使用
INSTALLED_APPS = [
        'graphene_django',
]

GRAPHENE = {
    'SCHEMA': 'app.schema.schema'
}

urls.py
from graphene_django.views import GraphQLView
from app.schema import schema

    path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)),

app/schema.py
from django.contrib.auth.models import  User  as Users
from graphene_django import DjangoObjectType
import graphene

#      https://passwo.gitbook.io/graphql/index/drf
class UserType(DjangoObjectType):
    class Meta:
        model = Users

class Query(graphene.ObjectType):
    users = graphene.List(UserType)

    # List == Field:
    # List               
    # Field           (       , ex. pk)
    single_user = graphene.Field(UserType, pk=graphene.Int())

    #         : resolve_  
    # **kwargs     
    # pk:         ,         
    def resolve_users(self, info, **kwargs):
        return Users.objects.all()

    def resolve_single_user(self, info, pk):
        return Users.objects.get(id=pk)

class TQuery(Query, graphene.ObjectType):
    pass

class CreateUser(graphene.Mutation):
    class Arguments:
        username = graphene.String(required=True)

    info = graphene.Field(UserType)
    ok = graphene.Boolean()

    def mutate(self, info, **kwargs):
        # print(info.context.user, '==    ==')
        # kwargs          
        # user = info.context.user
        user_obj = Users(**kwargs)
        try:
            user_obj.save()
            ok = True
        except Exception as e:
            print(e)
            ok = False
        return CreateUser(ok=ok, info=user_obj)

class CMutation(object):
    create_user = CreateUser.Field()

class UpdateUser(graphene.Mutation):
    class Arguments:
        username = graphene.String()
        pk = graphene.Int(required=True)

    info = graphene.Field(UserType)
    ok = graphene.Boolean()

    def mutate(self, info, **kwargs):
        pk = kwargs.get('pk')
        user_obj = Users.objects.get(id=pk)
        if not user_obj:
            return UpdateUser(ok=False)
        user_obj.__dict__.update(**kwargs)
        user_obj.save()
        ok = True
        return UpdateUser(ok=ok, info=user_obj)

class UMutation(object):
    update_user = UpdateUser.Field()

class DeleteUser(graphene.Mutation):
    class Arguments:
        pk = graphene.Int()

    ok = graphene.Boolean()

    def mutate(self, info, **kwargs):
        pk = kwargs.get('pk')

        user = Users.objects.get(id=pk)
        user.delete()
        return DeleteUser(ok=True)

class DMutation(object):
    delete_user = DeleteUser.Field()

class Mutations(CMutation, UMutation,DMutation,graphene.ObjectType):
    pass

schema = graphene.Schema(query=TQuery, mutation=Mutations)

リクエスト
要求アドレス:http://localhost/graphql
GraphQL要求パラメータ
query{
  users{
    id,
    username,
    email
  }
}

query{
  singleUser(pk: 1){
    username,
    email
  }
}

mutation createUser {
 createUser (username: "test1") {
     info {
         id,
     },
     ok
 }
}

mutation updateUser {
 updateUser (pk:2,username: "test2") {
     info {
         id,
     },
     ok
 }
}

mutation deleteUser {
 deleteUser (pk:2) {
     ok
 }
}