• graphene-django的简单示例


    1、所需要的安装包:

      graphene 2.1.8 Django 3.0.8  graphene-django 2.11.0

    2、创建一个model

    from django.db import models
    
    # Create your models here.
    
    from django.db import models
    
    class User(models.Model):
        name = models.CharField(max_length=100)
        gender = models.CharField(max_length=100)
    

    3、app下建立一个schema文件

    import graphene
    from .models import User
    from graphene import relay
    from graphene_django import DjangoObjectType, DjangoConnectionField
    
    class UserType(DjangoObjectType):
    
        class Meta:
            model = User
            interfaces = (relay.Node,)
    
    
    class UserInput(graphene.InputObjectType):
        name = graphene.String(required=True)
        gender = graphene.String(required=True)
    
    
    class CreateUser(graphene.Mutation):
        # a输入
        class Arguments:
            user_data = UserInput(required=True)
    
        # 响应
        ok = graphene.Boolean()
        user = graphene.Field(UserType)
    
        def mutate(self, info, user_data):
            user = User.objects.create(name=user_data['name'], gender=user_data['gender'])
            ok = True
            return CreateUser(user=user, ok=ok)
    
    
    class Query(graphene.ObjectType):
        users = graphene.List(UserType)
        all_users = DjangoConnectionField(UserType)
    
        def resolve_users(self, info):
            return User.objects.all()
    

    4、项目目录新建schema文件

    import graphene
    import MyGraph.schema
    
    
    class Query(MyGraph.schema.Query):
        pass
    
    
    class Mutations(graphene.ObjectType):
        create_user = MyGraph.schema.CreateUser.Field()
    
    
    schema = graphene.Schema(query=Query, mutation=Mutations)
    

    5、配置url

    from django.contrib import admin
    from django.urls import path
    from graphene_django.views import GraphQLView
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path(r"graphql", GraphQLView.as_view(graphiql=True))
    ]
    

    6、settings修改

    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'graphene_django',
        'MyGraph'
    ]
    

      

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

    7、项目目录大致如图:

     8、运行django,访问http://127.0.0.1:8000/graphql

    9、添加一条数据

     10、查询一条数据

     

     

      

  • 相关阅读:
    kubernetes(七)二进制安装-worker节点安装
    kubernetes(六)二进制安装-master节点安装
    B树
    Nginx反向代理无法达到效果原因
    AVL树
    平衡二叉搜索树
    二叉搜索树
    二叉树
    js-day06-jQuery事件和DOM操作-练习题
    js-day05-JSON-jQuery初体验
  • 原文地址:https://www.cnblogs.com/qinghuaL/p/13264465.html
Copyright © 2020-2023  润新知