最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

GraphQL在Django中的使用教程

 更新時(shí)間:2022年12月26日 10:19:14   作者:Mr.Lee jack  
這篇文章主要介紹了GraphQL在Django中的使用教程,本文結(jié)合示例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

簡介

特點(diǎn)

  • 請求你所要的數(shù)據(jù),不多不少
  • 獲取多個(gè)資源,只用一個(gè)請求
  • 描述所有的可能,類型系統(tǒng)
  • 幾乎所有語言支持

文檔

Graphene-Python

GraphQL | A query language for your API

背景

  • 傳統(tǒng)restful的接口定義類型多,試圖簡化接口定義
  • django中使用restframework定義restful資源接口時(shí),可能會(huì)出現(xiàn)深度查詢,造成有時(shí)候查詢過度
  • 例如前端用戶需要查詢接口用于展示在下拉框時(shí),用戶僅需要id與value值時(shí),造成無用字段冗余,影響接口返回性能
  • 當(dāng)一張表字段較多時(shí),例如接口1一共有40個(gè)字段,A頁面需要5個(gè)字段做展示,B頁面需要另外10個(gè)字段展示,這時(shí)我們需要根據(jù)用戶需求定義返回接口提升性能,且數(shù)據(jù)不會(huì)被暴露

實(shí)際問題

問題

  • 請求數(shù)據(jù)量40kB可以根據(jù)用戶縮減,也就是返回?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ù)庫模型

from django.db import models


class Category(models.Model):
    name = models.CharField(max_length=100, help_text="名稱")
    id = models.BigAutoField(primary_key=True)


class Ingredient(models.Model):
    id = models.BigAutoField(primary_key=True)
    name = models.CharField(max_length=100, help_text="名稱")
    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


# 為查詢添加查詢總數(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 查看過濾
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 查詢過濾
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)


# 匯總操作類接口
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é)

  • 查詢時(shí),可以使用django_filter , 快速查詢
  • 用法基本和drf框架基本類似
  • 接口面涉及的深度查詢,通過connection實(shí)現(xiàn),如果返回字段中沒有改要求,將不會(huì)深度查詢

到此這篇關(guān)于GraphQL在Django中的使用教程的文章就介紹到這了,更多相關(guān)GraphQL在Django中的使用內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:

相關(guān)文章

  • python中的全局變量與局部變量解讀

    python中的全局變量與局部變量解讀

    這篇文章主要介紹了python中的全局變量與局部變量用法,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2024-06-06
  • python導(dǎo)出hive數(shù)據(jù)表的schema實(shí)例代碼

    python導(dǎo)出hive數(shù)據(jù)表的schema實(shí)例代碼

    這篇文章主要介紹了python導(dǎo)出hive數(shù)據(jù)表的schema實(shí)例代碼,小編覺得還是挺不錯(cuò)的,具有一定借鑒價(jià)值,需要的朋友可以參考下
    2018-01-01
  • 詳解利用裝飾器擴(kuò)展Python計(jì)時(shí)器

    詳解利用裝飾器擴(kuò)展Python計(jì)時(shí)器

    在本文中,云朵君將和大家一起了解裝飾器的工作原理,如何將我們之前定義的定時(shí)器類?Timer?擴(kuò)展為裝飾器,以及如何簡化計(jì)時(shí)功能,感興趣的可以了解一下
    2022-06-06
  • python socket實(shí)現(xiàn)聊天室

    python socket實(shí)現(xiàn)聊天室

    這篇文章主要為大家詳細(xì)介紹了python socket實(shí)現(xiàn)聊天室,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2021-07-07
  • 利用Python實(shí)現(xiàn)自制文件搜索小工具

    利用Python實(shí)現(xiàn)自制文件搜索小工具

    當(dāng)自己電腦文件很多還有點(diǎn)亂,不記得自己文件放哪里的時(shí)候,用電腦自帶的搜索文件,這個(gè)等待時(shí)間可慢了。所以我們不如自己用python做一個(gè)搜索工具!犄角旮旯的文件都能一秒鐘搜索出來的那種
    2022-09-09
  • python Tkinter版學(xué)生管理系統(tǒng)

    python Tkinter版學(xué)生管理系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了python Tkinter版學(xué)生管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2019-02-02
  • Python使用Flask Migrate模塊遷移數(shù)據(jù)庫

    Python使用Flask Migrate模塊遷移數(shù)據(jù)庫

    Flask-Migrate是一個(gè)為Flask應(yīng)用處理SQLAlchemy數(shù)據(jù)庫遷移的擴(kuò)展,使得可以通過Flask的命令行接口或者Flask-Scripts對數(shù)據(jù)庫進(jìn)行操作
    2022-07-07
  • Python使用xlrd輕松讀取Excel文件的示例代碼

    Python使用xlrd輕松讀取Excel文件的示例代碼

    本文主要介紹了使用 Python 的 xlrd 庫讀取 Excel 文件的方法,包括安裝、各種操作如工作表操作、單元格操作、行與列操作、處理不同數(shù)據(jù)類型、性能優(yōu)化、結(jié)合其他庫、自定義處理等,還提到了一些特殊情況的處理及自定義類封裝讀取邏輯,需要的朋友可以參考下
    2024-11-11
  • pyinstaller打包程序exe踩過的坑

    pyinstaller打包程序exe踩過的坑

    這篇文章主要介紹了pyinstaller打包exe踩過的坑,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2019-11-11
  • 用十張圖詳解TensorFlow數(shù)據(jù)讀取機(jī)制(附代碼)

    用十張圖詳解TensorFlow數(shù)據(jù)讀取機(jī)制(附代碼)

    這篇文章主要介紹了用十張圖詳解TensorFlow數(shù)據(jù)讀取機(jī)制(附代碼),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2018-02-02

最新評論

江西省| 金寨县| 盐边县| 南阳市| 伊川县| 连城县| 安徽省| 大余县| 永州市| 祁门县| 进贤县| 城市| 黔西县| 永德县| 共和县| 镇远县| 靖西县| 盱眙县| 新宾| 内乡县| 社会| 江川县| 松江区| 普定县| 霍山县| 屏山县| 吉林市| 治多县| 乌拉特前旗| 吉水县| 汉中市| 安泽县| 临泉县| 嘉禾县| 呼图壁县| 会泽县| 兴和县| 遂昌县| 桐柏县| 五华县| 龙里县|