FastAPI 學習之路(十八)表單與檔案
阿新 • • 發佈:2021-10-17
系列文章:
FastAPI 學習之路(一)fastapi--高效能web開發框架
FastAPI 學習之路(十二)介面幾個額外資訊和額外資料型別
FastAPI 學習之路(十三)Cookie 引數,Header引數
我們首先要安裝表單或者檔案處理的依賴
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], }
我們看下測試結果
多個檔案上傳也是可以的,也是簡單的。
文章首發在公眾號,歡迎關注。