django使用graphql的實(shí)例
一、開發(fā)環(huán)境
1、python3.6
2、django2.0
3、window10
二、項(xiàng)目搭建
1、創(chuàng)建一個(gè)虛擬空間mkvirtualenv 空間名
2、創(chuàng)建一個(gè)django項(xiàng)目
3、安裝graphql的依賴包
pip install graphene-django
4、創(chuàng)建一個(gè)組件blog
5、把組件blog及graphene_django注入到app中
6、在settings.py中配置mysql數(shù)據(jù)庫(kù)連接
三、書寫blog的內(nèi)容
1、在models.py中寫上數(shù)據(jù)模型
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='創(chuàng)建時(shí)間') class Blog(models.Model): title = models.CharField(max_length=100, verbose_name='標(biāo)題') user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL, verbose_name='博主名字') content = models.TextField(verbose_name='博客內(nèi)容') create_at = models.DateTimeField(auto_now_add=True, verbose_name='創(chuàng)建時(shí)間') update_at = models.DateTimeField(auto_now=True, verbose_name='更新時(shí)間')
2、新建一個(gè)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 # 定義動(dòng)作約素輸入類型 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) # 定義一個(gè)創(chuàng)建user的mutation class CreateUser(graphene.Mutation): # api的輸入?yún)?shù) class Arguments: user_data = UserInput(required=True) # api的響應(yīng)參數(shù) ok = graphene.Boolean() user = graphene.Field(UserType) # api的相應(yīng)操作,這里是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) # 定義一個(gè)創(chuàng)建博客的mutation class CreateBlog(graphene.Mutation): class Arguments: blog_data = BlogInput(required=True) blog = graphene.Field(BlogType) def mutate(self, info, blog_data): # 插入到數(shù)據(jù)庫(kù)中 blog = Blog.objects.create(title=blog_data['title'], user_id=blog_data['user'], content=blog_data['content']) return CreateBlog(blog=blog) # 定義一個(gè)查詢語(yǔ)句 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同級(jí))創(chuàng)建一個(gè)項(xiàng)目的總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、生成數(shù)據(jù)庫(kù)映射及啟動(dòng)項(xiàng)目,直接在瀏覽器上訪問(wèn)
四、可以對(duì)上面的代碼調(diào)整
1、把Mutations也單獨(dú)定義在各自的schema.py中
# 定義一個(gè)總的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、輸入數(shù)據(jù)類型可以直接定義在mutation里面
class CreateUser(graphene.Mutation): # api的輸入?yún)?shù)(類名可以隨便定義) class Arguments: name = graphene.String(required=True) gender = graphene.String(required=True) # api的響應(yīng)參數(shù) ok = graphene.Boolean() user = graphene.Field(UserType) # api的相應(yīng)操作,這里是create def mutate(self, info, name, gender): user = User.objects.create(name=name, gender=gender) ok = True return CreateUser(user=user, ok=ok)
五、Query語(yǔ)句中使用條件查詢
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 # 定義一個(gè)查詢 class Query(object): # 定義一個(gè)根據(jù)id或者name查詢的 category = graphene.Field(CategoryType, id=graphene.Int(), name=graphene.String()) # 查詢?nèi)康? all_categories = graphene.List(CategoryType) # 根據(jù)條件查詢 ingredient = graphene.Field(IngredientType, id=graphene.Int(), name=graphene.String()) # 查詢?nèi)康? 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() # 定義查詢語(yǔ)句 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
補(bǔ)充知識(shí):記錄下python中使用定時(shí)器的幾種方法
方式一、直接使用while循環(huán)的方式
from datetime import datetime import time # 每n秒執(zhí)行一次 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 # 打印時(shí)間函數(shù) def print_time(inc): print(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) """ Timer的參數(shù)說(shuō)明 inc:表示時(shí)間間隔 print_time:執(zhí)行的函數(shù) (inc,):傳遞給執(zhí)行函數(shù)的參數(shù) """ t = Timer(inc, print_time, (inc,)) t.start() print_time(2)
方式三、使用sched模塊
import time import sched from datetime import datetime # 初始化 sched 模塊的 scheduler 類 # 第一個(gè)參數(shù)是一個(gè)可以返回時(shí)間戳的函數(shù),第二個(gè)參數(shù)可以在定時(shí)未到達(dá)之前阻塞。 schedule = sched.scheduler(time.time, time.sleep) # 被周期性調(diào)度觸發(fā)的函數(shù) def print_time(inc): print(datetime.now().strftime("%Y-%m-%d %H:%M:%S")) schedule.enter(inc, 0, print_time, (inc,)) # 默認(rèn)參數(shù) 60 s def start(inc=60): # enter四個(gè)參數(shù)分別為:間隔事件、優(yōu)先級(jí)(用于同時(shí)間到達(dá)的兩個(gè)事件同時(shí)執(zhí)行時(shí)定序)、被調(diào)用觸發(fā)的函數(shù)、給觸發(fā)函數(shù)的參數(shù)(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的實(shí)例就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
關(guān)于tensorflow的幾種參數(shù)初始化方法小結(jié)
今天小編就為大家分享一篇關(guān)于tensorflow的幾種參數(shù)初始化方法小結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-01-01python監(jiān)控nginx端口和進(jìn)程狀態(tài)
這篇文章主要為大家詳細(xì)介紹了python監(jiān)控nginx端口和進(jìn)程狀態(tài),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09Django模板導(dǎo)入母版繼承和自定義返回Html片段過(guò)程解析
這篇文章主要介紹了Django模板導(dǎo)入母版繼承和自定義返回Html片段過(guò)程解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-09-09Eclipse中Python開發(fā)環(huán)境搭建簡(jiǎn)單教程
這篇文章主要為大家分享了Eclipse中Python開發(fā)環(huán)境搭建簡(jiǎn)單教程,步驟簡(jiǎn)潔,一目了然,可以幫助大家快速搭建python開發(fā)環(huán)境,感興趣的小伙伴們可以參考一下2016-03-03Python實(shí)現(xiàn)定時(shí)任務(wù)利器之a(chǎn)pscheduler使用詳解
在Python中,還可以用第三方包來(lái)管理定時(shí)任務(wù),比如celery、apscheduler。相對(duì)來(lái)說(shuō)apscheduler使用起來(lái)更簡(jiǎn)單一些,這里來(lái)介紹一下apscheduler的使用方法2022-10-10Linux下升級(jí)安裝python3.8并配置pip及yum的教程
這篇文章主要介紹了Linux下升級(jí)安裝python3.8并配置pip及yum的教程,本文給大家介紹的非常詳細(xì),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-01-01詳解python使用pip安裝第三方庫(kù)(工具包)速度慢、超時(shí)、失敗的解決方案
這篇文章主要介紹了詳解python使用pip安裝第三方庫(kù)(工具包)速度慢、超時(shí)、失敗的解決方案,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-12-12詳解四種Python中基本形態(tài)學(xué)濾波的實(shí)現(xiàn)
最基礎(chǔ)的形態(tài)學(xué)操作有四個(gè),分別是腐蝕、膨脹、開計(jì)算和閉計(jì)算。這篇文章主要介紹了這四種形態(tài)學(xué)濾波的實(shí)現(xiàn),感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2023-04-04