• 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、查询一条数据

     

     

      

  • 相关阅读:
    因浮动问题导致的IE6/7下的换行
    弹性回到顶部js代码
    页面图片的缩放问题
    js练习小结
    地址给的越精确,优先级越高
    判断IE浏览器的版本
    img图像对齐的方式
    三级导航收缩下拉框
    功能已经实现
    AE创建一个空白的Shapefile
  • 原文地址:https://www.cnblogs.com/qinghuaL/p/13264465.html
Copyright © 2020-2023  润新知