django+graphql的基础配置

官网地址

一、开发环境

  • 1、python3.6
  • 2、django2.0
  • 3、window10

二、项目搭建

  • 1、创建一个虚拟空间mkvirtualenv 空间名

  • 2、创建一个django项目

  • 3、安装graphql的依赖包

    pip install graphene-django
    
  • 4、创建一个组件blog

  • 5、把组件bloggraphene_django注入到app

  • 6、在settings.py中配置mysql数据库连接

三、书写blog的内容

  • 1、在models.py中写上数据模型

    from django.db import models
    
    
    # Create your models here.
    class User(models.Model):
        name = models.CharField(max_length=100, verbose_name="博主名字")
        gender = models.CharField(max_length=6, choices=(('male', u'男'), ('female', '女')), default='female',
                                  verbose_name='性别')
        create_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    
    
    class Blog(models.Model):
        title = models.CharField(max_length=100, verbose_name='标题')
        user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='博主名字')
        content = models.TextField(verbose_name='博客内容')
        create_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
        update_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    
  • 2、新建一个schema.py文件

    #!/usr/bin/env python
    # encoding: utf-8
    
    import graphene
    from graphene_django.types import DjangoObjectType
    from .models import User, Blog
    
    
    class UserType(DjangoObjectType):
        class Meta:
            model = User
    
    
    class BlogType(DjangoObjectType):
        class Meta:
            model = Blog
    
    
    # 定义动作约素输入类型
    class UserInput(graphene.InputObjectType):
        name = graphene.String(required=True)
        gender = graphene.String(required=True)
    
    
    class BlogInput(graphene.InputObjectType):
        title = graphene.String(required=True)
        user = graphene.Int(required=True)
        content = graphene.String(required=True)
    
    
    # 定义一个创建user的mutation
    class CreateUser(graphene.Mutation):
        # api的输入参数
        class Arguments:
            user_data = UserInput(required=True)
    
        # api的响应参数
        ok = graphene.Boolean()
        user = graphene.Field(UserType)
    
        # api的相应操作,这里是create
        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)
    
    
    # 定义一个创建博客的mutation
    class CreateBlog(graphene.Mutation):
        class Arguments:
            blog_data = BlogInput(required=True)
    
        blog = graphene.Field(BlogType)
    
        def mutate(self, info, blog_data):
            # 插入到数据库中
            blog = Blog.objects.create(title=blog_data['title'], user_id=blog_data['user'], content=blog_data['content'])
            return CreateBlog(blog=blog)
    
    # 定义一个查询语句
    class Query(object):
        all_user = graphene.List(UserType)
        all_blog = graphene.List(BlogType)
    
        def resolve_all_user(self, info, **kwargs):
            # 查询所有book的逻辑
            return User.objects.all()
    
        def resolve_all_blog(self, info, **kwargs):
            # 查询所有title的逻辑
            return Blog.objects.all()
    
    
  • 3、在跟目录(和settings.py同级)创建一个项目的总schema.py

    import graphene
    import book.schema, blog.schema
    
    
    class Query(blog.schema.Query, graphene.ObjectType):
        # 总的Schema的query入口
        pass
    
    
    class Mutations(graphene.ObjectType):
        # 总的Schema的mutations入口
        create_user = blog.schema.CreateUser.Field()
        create_blog = blog.schema.CreateBlog.Field()
    
    
    schema = graphene.Schema(query=Query, mutation=Mutations)
    
  • 4、配置url地址

    from django.contrib import admin
    from django.urls import path
    from graphene_django.views import GraphQLView
    from .schema import schema
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('graphql/', GraphQLView.as_view(graphiql=True, schema=schema)),
    ]
    
  • 5、生成数据库映射及启动项目,直接在浏览器上访问

四、可以对上面的代码调整

  • 1、把Mutations也单独定义在各自的schema.py

    # 定义一个总的mutation出口
    class Mutation(graphene.AbstractType):
        create_user = CreateUser.Field()
        create_blog = CreateBlog.Field()
    
  • 2、在总的schema.py中引入类型Query一样的操作

    class Mutations(blog.schema.Mutation, graphene.ObjectType):
        # 总的Schema的mutations入口
        pass
    
  • 3、输入数据类型可以直接定义在mutation里面

    class CreateUser(graphene.Mutation):
        # api的输入参数(类名可以随便定义)
        class Arguments:
            name = graphene.String(required=True)
            gender = graphene.String(required=True)
    
        # api的响应参数
        ok = graphene.Boolean()
        user = graphene.Field(UserType)
    
        # api的相应操作,这里是create
        def mutate(self, info, name, gender):
            user = User.objects.create(name=name, gender=gender)
            ok = True
            return CreateUser(user=user, ok=ok)
    

五、Query语句中使用条件查询

  • 1、appschema(官方案例)

    import graphene
    from graphene_django.types import DjangoObjectType
    from .models import Category, Ingredient
    
    
    class CategoryType(DjangoObjectType):
        class Meta:
            model = Category
    
    
    class IngredientType(DjangoObjectType):
        class Meta:
            model = Ingredient
    
    
    # 定义一个查询
    class Query(object):
        # 定义一个根据id或者name查询的
        category = graphene.Field(CategoryType,
                                  id=graphene.Int(),
                                  name=graphene.String())
        # 查询全部的
        all_categories = graphene.List(CategoryType)
        # 根据条件查询
        ingredient = graphene.Field(IngredientType,
                                    id=graphene.Int(),
                                    name=graphene.String())
        # 查询全部的
        all_ingredients = graphene.List(IngredientType)
    
        def resolve_all_categories(self, info, **kwargs):
            return Category.objects.all()
    
        def resolve_all_ingredients(self, info, **kwargs):
            # We can easily optimize query count in the resolve method
            return Ingredient.objects.select_related('category').all()
    
        # 定义查询语句
        def resolve_category(self, info, **kwargs):
            id = kwargs.get('id')
            name = kwargs.get('name')
    
            if id is not None:
                return Category.objects.get(pk=id)
    
            if name is not None:
                return Category.objects.get(name=name)
    
            return None
    
        def resolve_ingredient(self, info, **kwargs):
            id = kwargs.get('id')
            name = kwargs.get('name')
    
            if id is not None:
                return Ingredient.objects.get(pk=id)
    
            if name is not None:
                return Ingredient.objects.get(name=name)
    
            return None
    

六、源码下载

七、查看博主更多文章

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

水痕01

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值