系列文章:
FastAPI 學習之路(一)fastapi--高性能web開發框架
FastAPI 學習之路(二)
FastAPI 學習之路(三)
FastAPI 學習之路(四)
FastAPI 學習之路(五)
FastAPI 學習之路(六)查詢引數,字串的校驗
FastAPI 學習之路(七)字串的校驗
FastAPI 學習之路(八)路徑引數和數值的校驗
FastAPI 學習之路(九)請求體有多個引數如何處理?
FastAPI 學習之路(十)請求體的欄位
FastAPI 學習之路(十一)請求體 - 嵌套模型
FastAPI 學習之路(十二)介面幾個額外資訊和額外資料型別
FastAPI 學習之路(十三)Cookie 引數,Header引數
FastAPI 學習之路(十四)回應模型
FastAPI 學習之路(十五)回應狀態碼
FastAPI 學習之路(十六)Form表單
FastAPI 學習之路(十七)上傳檔案
我們首先要安裝表單或者檔案處理的依賴
pip install python-multipart
我們去實作下上傳和form表單的組合使用
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: bytes = File(...), one: UploadFile = File(...),
token: str = Form(...)
):
return {
"filesize": len(file),
"token": token,
"one_content_type": one.content_type,
}
我們去看下介面請求試試,

宣告檔案可以使用 bytes 或 UploadFile,可在一個路徑操作中宣告多個 File 與 Form 引數,但不能同時宣告要接收 JSON 的 Body 欄位,因為此時請求體的編碼為 multipart/form-data
當然我們也可以上傳多個檔案,實作也很簡單,代碼如下
from fastapi import FastAPI, File, Form, UploadFile from typing import List app = FastAPI() @app.post("/files/") async def create_file( file: bytes = File(...), one: List[UploadFile] = File(...), token: str = Form(...) ): return { "filesize": len(file), "token": token, "one_content_type": [file.content_type for file in one], }
我們看下測驗結果


多個檔案上傳也是可以的,也是簡單的,
文章首發在公眾號,歡迎關注,

轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/320887.html
標籤:其他
