- FastAPI 教程
- FastAPI - 主頁
- FastAPI - 簡介
- FastAPI - Hello World
- FastAPI - OpenAPI
- FastAPI - Uvicorn
- FastAPI - 型別提示
- FastAPI - IDE 支援
- FastAPI - REST 體系結構
- FastAPI - 路徑引數
- FastAPI - 查詢引數
- FastAPI - 引數驗證
- FastAPI - Pydantic
- FastAPI - 請求正文
- FastAPI - 模板
- FastAPI - 靜態檔案
- FastAPI - HTML 表單模板
- FastAPI - 訪問表單資料
- FastAPI - 上傳檔案
- FastAPI - Cookie 引數
- FastAPI - Header 引數
- FastAPI - 響應模型
- FastAPI - 巢狀模型
- FastAPI - 依賴項
- FastAPI - CORS
- FastAPI - CRUD 操作
- FastAPI - SQL 資料庫
- FastAPI - 使用 MongoDB
- FastAPI - 使用 GraphQL
- FastAPI - Websockets
- FastAPI - FastAPI 事件處理程式
- FastAPI - 掛載子應用
- FastAPI - 中介軟體
- FastAPI - 掛載 Flast 應用程式
- FastAPI - 部署
- FastAPI 實用資源
- FastAPI - 快速指南
- FastAPI - 實用資源
- FastAPI - 討論
FastAPI - 巢狀模型
**Pydantic** 模型的每個屬性都具有一種型別。該型別可以是 Python 內建型別,也可以是模型本身。因此,可以宣告具有特定屬性名稱、型別和驗證的巢狀 JSON“物件”。
示例
在以下示例中,我們構建一個客戶模型,其中一個屬性為產品模型類。產品模型又具有供應商類屬性。
from typing import Tuple from fastapi import FastAPI from pydantic import BaseModel app = FastAPI() class supplier(BaseModel): supplierID:int supplierName:str class product(BaseModel): productID:int prodname:str price:int supp:supplier class customer(BaseModel): custID:int custname:str prod:Tuple[product]
以下 POST 操作裝飾器將客戶模型的物件呈現為伺服器響應。
@app.post('/invoice')
async def getInvoice(c1:customer):
return c1
swagger UI 頁面顯示存在三個模式,對應於三個 BaseModel 類。
Customer 模式在展開以顯示所有節點的情況下如下所示 -
**"/invoice"** 路由的一個示例響應如下 -
{
"custID": 1,
"custname": "Jay",
"prod": [
{
"productID": 1,
"prodname": "LAPTOP",
"price": 40000,
"supp": {
"supplierID": 1,
"supplierName": "Dell"
}
}
]
}
廣告