Python API開發,FastAPI之Graphql版本!_v1.0.2

文件名稱 版本號 作者 qq 版本
Python API開發,FastAPI之Graphql版本! v1.0.2 學生宮布 8416837 Python 3.8
FastAPI (0.1.0)

源碼

Demo

點擊查看Demo源碼

簡介

  • Graphql是一種神奇的技術,它是API查詢語言,傳什麼參數獲得啥結果,等等神奇妙用。進入官網
  • Graphql不受編程語言限制,Java、Python、JavaScript、C# / .NET等等都支持。查看支持的語言
  • 在這裏插入圖片描述

安裝

安裝FastAPI見 FastAPI安裝教程

試水

使用Conda

  • 當前使用的是Conda 4.8.2。安裝教程:查看教程
    在這裏插入圖片描述
  • 安裝依賴庫
pip3 install graphene

使用IDE開發 比如:PyCharm

配置
  • 如果已經打開了項目窗口,則新建Python Package
    *
  • 新建文件等:
    *
代碼
  • 向main.py拷入代碼:
import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp


class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value="stranger"))

    def resolve_hello(self, info, name):
        return "Hello " + name


app = FastAPI()
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))
  • 安裝依賴庫 否則會報錯如下:
    *
    安裝:
pip3 install graphene

在這裏插入圖片描述

啓動項目
  • 打開gitbash,定位到main.py所在目錄,執行命令:
uvicorn main:app --reload
訪問項目

在這裏插入圖片描述
啓動完畢,訪問項目

頁面解釋
  • UI在這裏插入圖片描述
  • 釋義
    在這裏插入圖片描述
調用Graphql API
  • 傳入參數,獲得響應:
    在這裏插入圖片描述
    之所以傳入{hello},可以獲得響應:
{
  "data": {
    "hello": "Hello stranger"
  }
}

是因爲代碼裏寫了這個接口解析,它是這樣的:
在這裏插入圖片描述

  • 參數更復雜一點:
    在這裏插入圖片描述
進階
  • 將代碼整得稍微複雜一點:
import json
import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp


class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value="stranger"))

    def resolve_hello(self, info, name):
        return "Hello " + name

    login_in = graphene.String(username=graphene.String(default_value="administrator"))

    def resolve_login_in(self, info, username):
        data = [{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}]

        json2 = json.dumps(data)

        return "Hello " + username

app = FastAPI()
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))

執行,獲得響應:
在這裏插入圖片描述

  • 加個判斷:
import json

import graphene
from fastapi import FastAPI
from starlette.graphql import GraphQLApp

# 生成gql的Query
class Query(graphene.ObjectType):
    hello = graphene.String(name=graphene.String(default_value="stranger"))

    def resolve_hello(self, info, name):
        return "Hello " + name

    login_in = graphene.String(username=graphene.String(default_value="administrator"))

    def resolve_login_in(self, info, username):
        return "Hello " + username

    login = graphene.String(username=graphene.String(default_value="administrator"))
    graphene.ObjectType

    def resolve_login(self, info, username):

        name = '李甲'
        if(name.__eq__(username)):
            data = [{'username': '李甲', 'b': 2, 'c': 3, 'd': 4, 'e': 5}]

            json2 = json.dumps(data)

            return json2
        else :
            return ""


app = FastAPI()
app.add_route("/", GraphQLApp(schema=graphene.Schema(query=Query)))

響應:
在這裏插入圖片描述
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章