为什么不用REST
- Rest一次只能请求一个资源,会造成太多的http请求
- Rest的版本控制问题是一个痛
GraphQL的关键语句
- query:查询,相当于GET
- mutation:变化,相当于POST, PUT, DELETE
环境搭建
- win10
- Python3.6
- pip install django==2.0.1
- pip install graphene-django==2.0.0
创建项目
django-admin.py startproject django_graphql
cd django_graphql
python startapp book
- 项目的文件组织
![](https://img-blog.csdn.net/20180222181021607?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbnMyMjUwMjI1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
创建model
from django.db import models
class Title(models.Model):
title = models.CharField(max_length=255, verbose_name="标题")
def __str__(self):
return self.name
class Author(models.Model):
name = models.CharField(max_length=255, verbose_name="作者姓名")
def __str__(self):
return self.name
class Book(models.Model):
title = models.ForeignKey(Title, related_name='book_title', on_delete=models.CASCADE)
author = models.ForeignKey(Author, related_name='book_author', on_delete=models.CASCADE)
创建schema.py
import graphene
from graphene_django.types import DjangoObjectType
from .models import Book, Title, Author
class BookType(DjangoObjectType):
class Meta:
model = Book
class TitleType(DjangoObjectType):
class Meta:
model = Title
class AuthorType(DjangoObjectType):
class Meta:
model = Author
class BookInput(graphene.InputObjectType):
title = graphene.String(required=True)
author = graphene.String(required=True)
class CreateBook(graphene.Mutation):
class Arguments:
book_data = BookInput(required=True)
ok = graphene.Boolean()
book = graphene.Field(BookType)
def mutate(self, info, book_data):
title = Title.objects.create(title=book_data['title'])
author = Author.objects.create(name=book_data['author'])
book = Book.objects.create(title=title, author=author)
ok = True
return CreateBook(book=book, ok=ok)
class Query(object):
all_books = graphene.List(BookType)
all_titles = graphene.List(TitleType)
all_authors = graphene.List(AuthorType)
def resolve_all_books(self, info, **kwargs):
return Book.objects.all()
def resolve_all_titles(self, info, **kwargs):
return Book.objects.select_related('book_title').all()
def resolve_all_authors(self, info, **kwargs):
return Book.objects.select_related('book_author').all()
创建总的schema入口文件
- 再settings.py的同级目录下创建:schema.py
# -*- coding: utf-8 -*-
# 总的schema入口
import graphene
import book.schema
class Query(book.schema.Query, graphene.ObjectType):
# 总的Schema的query入口
pass
class Mutations(graphene.ObjectType):
# 总的Schema的mutations入口
create_book = book.schema.CreateBook.Field()
schema = graphene.Schema(query=Query, mutation=Mutations)
配置总的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)),
]
启动项目
python manage.py makemigrations
python manage.py migrate
python manage.py runserver 0.0.0.0:8080
- 访问:
localhost:8080/graphql/
![](https://img-blog.csdn.net/20180222182120498?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbnMyMjUwMjI1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
创建book
mutation createBook {
createBook(bookData: {title:"django-graphgl2", author: "ns2250225"}) {
book {
title {
id,
title
},
author {
id,
name
}
}
ok
}
}
![](https://img-blog.csdn.net/20180222182305646?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbnMyMjUwMjI1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
查询book
query {
allBooks {
id,
title {
id,
title
},
author {
id,
name
}
}
}
![](https://img-blog.csdn.net/20180222182453897?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvbnMyMjUwMjI1/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
Github