您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關在django如何正確的使用graphql,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
一、開發環境
1、python3.6
2、django2.0
3、window10
二、項目搭建
1、創建一個虛擬空間mkvirtualenv 空間名
2、創建一個django項目
3、安裝graphql的依賴包
pip install graphene-django
4、創建一個組件blog
5、把組件blog及graphene_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、app的schema(官方案例)
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
官網地址
補充知識:記錄下python中使用定時器的幾種方法
方式一、直接使用while循環的方式
from datetime import datetime import time # 每n秒執行一次 def timer(n): while True: print(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) time.sleep(n) timer(5)
方式二、使用threading模塊中的Timer
from datetime import datetime from threading import Timer # 打印時間函數 def print_time(inc): print(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) """ Timer的參數說明 inc:表示時間間隔 print_time:執行的函數 (inc,):傳遞給執行函數的參數 """ t = Timer(inc, print_time, (inc,)) t.start() print_time(2)
方式三、使用sched模塊
import time import sched from datetime import datetime # 初始化 sched 模塊的 scheduler 類 # 第一個參數是一個可以返回時間戳的函數,第二個參數可以在定時未到達之前阻塞。 schedule = sched.scheduler(time.time, time.sleep) # 被周期性調度觸發的函數 def print_time(inc): print(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) schedule.enter(inc, 0, print_time, (inc,)) # 默認參數 60 s def start(inc=60): # enter四個參數分別為:間隔事件、優先級(用于同時間到達的兩個事件同時執行時定序)、被調用觸發的函數、給觸發函數的參數(tuple形式) schedule.enter(0, 0, print_time, (inc,)) schedule.run() if __name__ == "__main__": start(10)
方式四、使用apscheduler
from apscheduler.schedulers.blocking import BlockingScheduler from datetime import datetime def job(): print(datetime.now().strftime('%Y-%m-%d %H:%M:%S')) if __name__ == "__main__": scheduler = BlockingScheduler() scheduler.add_job(job, 'interval', seconds=5) scheduler.start()
關于在django如何正確的使用graphql就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。