天天看點

FastAPI 快速上手,FastAPI程式模版FastAPI快速上手

FastAPI快速上手

本文主要是分享如何快速上手fastAPI,如果讀者已經有flask sanic django等架構的使用經驗,那麼本文應該沒有太大的閱讀難度。官方文檔,本文會盡可能避免将文章寫成官方文檔。

有關fastAPI 的安裝直接看官方文檔

階段1

項目結構

└── fastAPI_app
    └── run.py
           

code

# fastAPI_app/run.py
from fastapi import FastAPI

fastApp = FastAPI()

@fastApp.get('/test')
async def get():
    return {"msg": "hello"}

# uvicorn app:app --reload
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(fastApp, host='127.0.0.1', port=9998)
           

與flask很像,特别像,fastAPI還提供了一個互動式的API文檔,執行

python run.py

,然後在浏覽器輸入http://127.0.0.1:9998/docs就可以看到

FastAPI 快速上手,FastAPI程式模版FastAPI快速上手

點選 這個接口進入

FastAPI 快速上手,FastAPI程式模版FastAPI快速上手

再點選try it out

FastAPI 快速上手,FastAPI程式模版FastAPI快速上手

現在可以點解 excute,就可以測試該接口了,有用過Swagger的人應該都知道,沒用過的可以自己去探索一下。

請求體

有關請求參數、查詢參數等,這裡不浪費口舌了,這裡就說明一下 post方法傳入json格式的參數。官方文檔

#fastAPI_app/run.py
from fastapi import FastAPI
from pydantic import BaseModel

from typing import Optional

fastApp = FastAPI()

@fastApp.get('/test')
async def get():
    return {"msg": "hello"}

# declare a request body
class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None

# 如果僅僅是用來python類型聲明,fastAPI 會将請求體作為JSON讀取
@fastApp.post("/test/item_query/")
async def create_item(item: Item):
    item_dict = item.dict()
    if item.tax:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
    return item_dict

# uvicorn app:app --reload
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(fastApp, host='127.0.0.1', port=9998)
           

執行檔案,接着在Swagger中測試,使用pydantic可以直接限制請求體,fastAPI會把你定義的model解析成JSON并在Swagger中直接展現出來。當然了我們也可以使用Body,有關查詢參數、路徑參數、header參數、cookie參數等,看文檔。

階段2

項目結構

└── fastAPI_app
    ├── app
    │   ├── __init__.py
    │   └── routers
    │       ├── __init__.py
    │       └── test.py
    └── run.py
           

code

# fastAPI_app/run.py
from app import create_app

fastApp = create_app()

# uvicorn app:app --reload
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(fastApp, host='127.0.0.1', port=9998)
           
#fastAPI_app/app/__init__.py
from fastapi import FastAPI

from app.routers import testRouter

def add_router(app: FastAPI):
    app.include_router(testRouter)

def create_app():
    app = FastAPI()
    add_router(app)

    return app
           
#fastAPI_app/app/routers/test.py
from fastapi import APIRouter
from pydantic import BaseModel

from typing import Optional


testRouter = APIRouter()

@testRouter.get('/test')
async def get():
    return {"msg": "hello"}

# declare a request body
class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None


@testRouter.post("/test/item_query/")
async def create_item(item: Item):
    item_dict = item.dict()
    if item.tax:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
    return item_dict
           
#fastAPI_app/app/routers/__init__.py
from .test import testRouter
           

相比于階段1,功能沒有任何變化,隻是改變了項目結構,同時引入了新的FastAPI路由使用方法,如果你使用過flask的blueprint,這個基本上也就沒多大難度了,文檔連結,我在routers目錄下建立了test.py檔案,并在這裡建立了一個路由執行個體,最後将這個路由執行個體挂載在app執行個體上。這樣做的好處就是,代碼幹淨。

視圖模型

之前在routers中的test.py中建立了model,可以把這個model遷移出來

└── fastAPI_app
    ├── app
    │   ├── __init__.py
    │   ├── routers
    │   │   ├── __init__.py
    │   │   └── test.py
    │   └── view_models
    │       ├── __init__.py
    │       └── test.py
    └── run.py
           
#fastAPI_app/app/routers/test.py
from fastapi import APIRouter
from app.view_models.test import Item

testRouter = APIRouter()

@testRouter.get('/test')
async def get():
    return {"msg": "hello"}

@testRouter.post("/test/item_query/")
async def create_item(item: Item):
    item_dict = item.dict()
    if item.tax:
        price_with_tax = item.price + item.tax
        item_dict.update({"price_with_tax": price_with_tax})
    return item_dict
           
#fastAPI_app/app/view_models/test.py
from pydantic import BaseModel
from typing import Optional

# declare a request body
class Item(BaseModel):
    name: str
    description: Optional[str] = None
    price: float
    tax: Optional[float] = None
           

現在,這個項目已經有點眉目了,使用視圖模型和路由共同解析使用者傳來的參數,并在路由中處理參數并傳回結果,接着就是要操作資料庫了,我們肯定不希望在路由中操作資料庫。

階段3

├── FastAPI_base
│   ├── app
│   │   ├── __init__.py
│   │   ├── controller
│   │   │   ├── __init__.py
│   │   │   └── test.py
│   │   ├── data
│   │   │   └── test.db
│   │   ├── models
│   │   │   ├── __init__.py
│   │   │   └── test.py
│   │   ├── routers
│   │   │   ├── __init__.py
│   │   │   └── test.py
│   │   └── view_models
│   │       ├── __init__.py
│   │       └── test.py
│   ├── requirements.txt
│   └── run.py
           

此處新添加了controller和models,models用來定義ORM模型,controller中定義增删改查,當使用者的請求需要操作資料庫時,會在路由中調用controller,簡單的MVC架構。SQL FastAPI

,在官方文檔中使用的是 SQLAlchemy,是以,如果你有一套屬于自己風格的db操作方法,可以跳過了。具體的代碼可以在筆者的項目中檢視FastAPI_base,筆者的目标是根據官方文檔完成一個FastAPI程式模版,類似于flask_base那樣,後續會嘗試添加 async_sql, GraphQL, WebSocket等,也希望有人可以一起參與其中,共同學習。