
ASP.NET Web API快速入門介紹
pip install graphene-django
2、生成 Django 初始代碼,編寫 models.py,編寫 GraphQL 的模式。
django-admin startproject cookbook
cd cookbook
python manage.py startapp ingredients
修改 models.py 文件,添加兩個類,一個是對應分類,別一個對應原料,修改后內容如下所示:
from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Ingredient(models.Model):
name = models.CharField(max_length=100)
notes = models.TextField()
category = models.ForeignKey(
Category, related_name="ingredients", on_delete=models.CASCADE
)
def __str__(self):
return self.name
外鍵代表兩者之間的關系:一個分類下面可以有多個原料,但一個原料只能屬于某一個分類。
然后,我們在 settings.py 同一級的目錄,新增一個 schema.py 文件,內容如下:
import graphene
from graphene_django import DjangoObjectType
from ingredients.models import Category, Ingredient
class CategoryType(DjangoObjectType):
class Meta:
model = Category
fields = ("id", "name", "ingredients")
class IngredientType(DjangoObjectType):
class Meta:
model = Ingredient
fields = ("id", "name", "notes", "category")
class Query(graphene.ObjectType):
all_ingredients = graphene.List(IngredientType)
all_categorys = graphene.List(CategoryType)
category_by_name = graphene.Field(CategoryType, name=graphene.String(required=True))
def resolve_all_categorys(root, info):
return Category.objects.all()
def resolve_all_ingredients(root, info):
# We can easily optimize query count in the resolve method
return Ingredient.objects.all()
def resolve_category_by_name(root, info, name):
try:
return Category.objects.get(name=name)
except Category.DoesNotExist:
return None
schema = graphene.Schema(query=Query)
schema 是 GraphQL 的核心代碼,Query 類和 models 類很像,對比著寫代碼就可以了,后面熟悉之后再理解它的原理。
接著,我們在 settings.py 的 INSTALLED_APPS 添加兩條記錄:
"ingredients.apps.IngredientsConfig",
"graphene_django",
配置 cookbook.urls 使用剛才創建的 schema, 內容如下:
from django.contrib import admin
from django.urls import path
from django.views.decorators.csrf import csrf_exempt
from graphene_django.views import GraphQLView
from cookbook.schema import schema
urlpatterns = [
path("admin/", admin.site.urls),
path("graphql/", csrf_exempt(GraphQLView.as_view(graphiql=True,schema=schema))),
]
3、建表,插入測試數據。
(py38env) ? cookbook python manage.py makemigrations
Migrations for 'ingredients':
ingredients/migrations/0001_initial.py
- Create model Category
- Create model Ingredient
(py38env) ? cookbook python manage.py migrate
Operations to perform:
Apply all migrations: admin, auth, contenttypes, ingredients, sessions
Running migrations:
Applying ingredients.0001_initial... OK
(py38env) ? cookbook ls
cookbook db.sqlite3 ingredients manage.py
至此,db.sqlite3 中已經有了兩張表,接下來插入測試數據,數據來源:ingredients.json
下載后保存到項目的根目錄,也就是第一個 cookbook 目錄下,然后執行下面的命令導入測試數據:
(py38env) ? cookbook python manage.py loaddata ingredients.json
Installed 6 object(s) from 1 fixture(s)
4、啟動服務,并測試。
python manage.py runserver
瀏覽器打開 http://localhost:8000/graphql/
就可以看到如下頁面:
這就是 GraphQL 的接口調試界面,左邊輸入查詢條件,右邊返回數據。
比如查一下所有的原料表:
query {
allIngredients {
id
name
note
}
}
接下來反著查一下,比如查詢所有的分類:
query {
allCategorys {
id
name
}
}
查詢所有的分類及對應的原料信息:
query {
allCategorys {
id
name
ingredients{
id
name
notes
}
}
}
查詢某一分類,比如乳制品分類下面的原料信息:
query {
categoryByName(name: "Dairy") {
id
name
ingredients {
id
name
}
}
}
GraphQL 非常強大,并且可以快速集成 Django 模型,從而可以非常方便的將你的應用 api 轉換為 GraphQL 風格。
文章轉自微信公眾號@Python七號