GraphQL在Django中的使用教程
簡(jiǎn)介
特點(diǎn)
- 請(qǐng)求你所要的數(shù)據(jù),不多不少
- 獲取多個(gè)資源,只用一個(gè)請(qǐng)求
- 描述所有的可能,類(lèi)型系統(tǒng)
- 幾乎所有語(yǔ)言支持
文檔
GraphQL | A query language for your API
背景
- 傳統(tǒng)restful的接口定義類(lèi)型多,試圖簡(jiǎn)化接口定義
- django中使用restframework定義restful資源接口時(shí),可能會(huì)出現(xiàn)深度查詢(xún),造成有時(shí)候查詢(xún)過(guò)度
- 例如前端用戶(hù)需要查詢(xún)接口用于展示在下拉框時(shí),用戶(hù)僅需要id與value值時(shí),造成無(wú)用字段冗余,影響接口返回性能
- 當(dāng)一張表字段較多時(shí),例如接口1一共有40個(gè)字段,A頁(yè)面需要5個(gè)字段做展示,B頁(yè)面需要另外10個(gè)字段展示,這時(shí)我們需要根據(jù)用戶(hù)需求定義返回接口提升性能,且數(shù)據(jù)不會(huì)被暴露
實(shí)際問(wèn)題
問(wèn)題
- 請(qǐng)求數(shù)據(jù)量40kB可以根據(jù)用戶(hù)縮減,也就是返回?cái)?shù)據(jù)量可以做到<40KB
- 后端數(shù)據(jù)實(shí)際耗時(shí)783ms,但是數(shù)據(jù)傳輸一共耗時(shí)5s
Django中如何使用呢
安裝
安裝
pip install graphene-django
django配置
INSTALLED_APPS = [ "django.contrib.staticfiles", "graphene_django" ] GRAPHENE = { "SCHEMA": "test_api.schema.schema" # 下文中需要定義schema.py文件 }
Demo
定義數(shù)據(jù)庫(kù)模型
from django.db import models class Category(models.Model): name = models.CharField(max_length=100, help_text="名稱(chēng)") id = models.BigAutoField(primary_key=True) class Ingredient(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=100, help_text="名稱(chēng)") notes = models.TextField(help_text="筆記") category = models.ForeignKey( Category, related_name="category", on_delete=models.CASCADE ) def __str__(self): return self.name
定義serializer
from graphene_django.rest_framework.mutation import SerializerMutation from rest_framework.serializers import ModelSerializer from ..models import Category, Ingredient class CategorySerializer(ModelSerializer): class Meta: model = Category fields = "__all__" class IngredientSerializer(ModelSerializer): class Meta: model = Ingredient fields = "__all__"
定義接口
import graphene from graphene import relay from graphene_django import DjangoObjectType from graphene_django.filter import DjangoFilterConnectionField from graphene_django.rest_framework.mutation import SerializerMutation from ..models import Category, Ingredient from ..serializer import CategorySerializer, IngredientSerializer # 為查詢(xún)添加查詢(xún)總數(shù) class CountableConnectionBase(relay.Connection): class Meta: abstract = True total_count = graphene.Int() def resolve_total_count(self, info, **kwargs): return self.iterable.count() # Ingredient 查看過(guò)濾 class IngredientFilter(DjangoObjectType): class Meta: model = Ingredient fields = "__all__" filter_fields = { "name": ['exact', "contains", "istartswith"], "category": ["exact"], 'category__name': ['exact'], } interfaces = (relay.Node,) connection_class = CountableConnectionBase extra_field = graphene.String() def resolve_extra_field(self: Ingredient, info): return "hello!" + str(self.id) # CategoryFilter 查詢(xún)過(guò)濾 class CategoryFilter(DjangoObjectType): class Meta: model = Category fields = "__all__" filter_fields = { "name": ['exact', "contains", "istartswith"], } interfaces = (relay.Node,) connection_class = CountableConnectionBase # CategoryMutation 修改或新增 class CategoryMutation(SerializerMutation): class Meta: serializer_class = CategorySerializer # IngredientMutation 修改或新增 class IngredientMutation(SerializerMutation): class Meta: serializer_class = IngredientSerializer # 匯總query接口 class ApiQuery(graphene.ObjectType): search_category = DjangoFilterConnectionField(CategoryFilter) search_ingredient = DjangoFilterConnectionField(IngredientFilter) # 匯總操作類(lèi)接口 class ApiMutation(graphene.ObjectType): update_category = CategoryMutation.Field() update_ingredient = IngredientMutation.Field()
匯總所有接口
import graphene from .api import ApiQuery, ApiMutation class Query(ApiQuery): # 新增時(shí)提供多繼承即可 pass class Mutation(ApiMutation): # 新增時(shí)提供多繼承即可 pass schema = graphene.Schema(query=Query, mutation=Mutation)
啟動(dòng)
python manage.py runserver 0.0.0.0:8080
接口文檔
總結(jié)
- 查詢(xún)時(shí),可以使用django_filter , 快速查詢(xún)
- 用法基本和drf框架基本類(lèi)似
- 接口面涉及的深度查詢(xún),通過(guò)connection實(shí)現(xiàn),如果返回字段中沒(méi)有改要求,將不會(huì)深度查詢(xún)
到此這篇關(guān)于GraphQL在Django中的使用教程的文章就介紹到這了,更多相關(guān)GraphQL在Django中的使用內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用python遠(yuǎn)程操作linux過(guò)程解析
這篇文章主要介紹了使用python遠(yuǎn)程操作linux過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-12-12在Python程序中實(shí)現(xiàn)分布式進(jìn)程的教程
這篇文章主要介紹了在Python程序中實(shí)現(xiàn)分布式進(jìn)程的教程,在多進(jìn)程編程中十分有用,示例代碼基于Python2.x版本,需要的朋友可以參考下2015-04-04Python讀取xlsx文件的實(shí)現(xiàn)方法
這篇文章主要介紹了Python讀取xlsx文件的實(shí)現(xiàn)方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-07-07Python 實(shí)用技巧之利用Shell通配符做字符串匹配
這篇文章主要介紹了Python 實(shí)用技巧之利用Shell通配符做字符串匹配的方法,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-08-08pandas pivot_table() 按日期分多列數(shù)據(jù)的方法
今天小編就為大家分享一篇pandas pivot_table() 按日期分多列數(shù)據(jù)的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-11-11