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

django使用graphql的實(shí)例

 更新時(shí)間:2020年09月02日 17:23:03   作者:水痕01  
這篇文章主要介紹了django使用graphql的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧

一、開發(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ù)庫連接

三、書寫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ù)庫中
  blog = Blog.objects.create(title=blog_data['title'], user_id=blog_data['user'], content=blog_data['content'])
  return CreateBlog(blog=blog)

# 定義一個(gè)查詢語句
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ù)庫映射及啟動(dòng)項(xiàng)目,直接在瀏覽器上訪問

四、可以對(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語句中使用條件查詢

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()

 # 定義查詢語句
 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

官網(wǎng)地址

補(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ù)說明
  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í)例就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:

相關(guān)文章

  • Python利用PyQT5設(shè)置鬧鐘功能

    Python利用PyQT5設(shè)置鬧鐘功能

    這篇文章主要介紹了通過PyQt5實(shí)現(xiàn)設(shè)置一個(gè)小鬧鐘的功能,到了設(shè)置的時(shí)間后可以響起一段音樂來提醒。感興趣的小伙伴可以跟隨小編一起試一試
    2022-01-01
  • python裝飾器相當(dāng)于函數(shù)的調(diào)用方式

    python裝飾器相當(dāng)于函數(shù)的調(diào)用方式

    今天小編就為大家分享一篇python裝飾器相當(dāng)于函數(shù)的調(diào)用方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-12-12
  • python3 遍歷刪除特定后綴名文件的方法

    python3 遍歷刪除特定后綴名文件的方法

    下面小編就為大家分享一篇python3 遍歷刪除特定后綴名文件的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2018-04-04
  • python pandas 解析(讀取、寫入)CSV 文件的操作方法

    python pandas 解析(讀取、寫入)CSV 文件的操作方法

    這篇文章主要介紹了python pandas 解析(讀取、寫入) CSV 文件,本文通過示例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2022-12-12
  • Python小知識(shí)之幾種推導(dǎo)式用法示例

    Python小知識(shí)之幾種推導(dǎo)式用法示例

    Python推導(dǎo)式是一種獨(dú)特的數(shù)據(jù)處理方式,可以從一個(gè)數(shù)據(jù)序列構(gòu)建另一個(gè)新的數(shù)據(jù)序列的結(jié)構(gòu)體,下面這篇文章主要給大家介紹了關(guān)于Python小知識(shí)之幾種推導(dǎo)式用法的相關(guān)資料,需要的朋友可以參考下
    2023-01-01
  • 使用keras內(nèi)置的模型進(jìn)行圖片預(yù)測實(shí)例

    使用keras內(nèi)置的模型進(jìn)行圖片預(yù)測實(shí)例

    這篇文章主要介紹了使用keras內(nèi)置的模型進(jìn)行圖片預(yù)測實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-06-06
  • 對(duì)python 多線程中的守護(hù)線程與join的用法詳解

    對(duì)python 多線程中的守護(hù)線程與join的用法詳解

    今天小編就為大家分享一篇對(duì)python 多線程中的守護(hù)線程與join的用法詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2019-02-02
  • Jupyter?Notebook界面漢化完整步驟

    Jupyter?Notebook界面漢化完整步驟

    這篇文章主要給大家介紹了關(guān)于Jupyter?Notebook界面漢化的相關(guān)資料,設(shè)置成中文界面后非常利于操作,文中介紹的方法非常簡單,需要的朋友可以參考下
    2023-09-09
  • python條件和循環(huán)的使用方法

    python條件和循環(huán)的使用方法

    下面我們來介紹python條件語句和循環(huán)語句的使用方法。
    2013-11-11
  • Python使用socketServer包搭建簡易服務(wù)器過程詳解

    Python使用socketServer包搭建簡易服務(wù)器過程詳解

    這篇文章主要介紹了Python使用socketServer包搭建簡易服務(wù)器過程詳解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2020-06-06

最新評(píng)論

加查县| 彩票| 平遥县| 通化县| 故城县| 那曲县| 抚顺市| 阜平县| 河西区| 麦盖提县| 广东省| 吉隆县| 方城县| 青田县| 沁源县| 邵武市| 千阳县| 新巴尔虎左旗| 滨州市| 青铜峡市| 牙克石市| 资中县| 个旧市| 莱芜市| 汉寿县| 张掖市| 宿松县| 那坡县| 宣城市| 调兵山市| 西华县| 阿荣旗| 安新县| 大足县| 通化县| 桃江县| 大名县| 东港市| 股票| 东辽县| 平阳县|