系列文章:
FastAPI 學習之路(一)fastapi--高性能web開發框架
FastAPI 學習之路(二)
FastAPI 學習之路(三)
FastAPI 學習之路(四)
FastAPI 學習之路(五)
FastAPI 學習之路(六)查詢引數,字串的校驗
FastAPI 學習之路(七)字串的校驗
FastAPI 學習之路(八)路徑引數和數值的校驗
FastAPI 學習之路(九)請求體有多個引數如何處理?
FastAPI 學習之路(十)請求體的欄位
FastAPI 學習之路(十一)請求體 - 嵌套模型
FastAPI 學習之路(十二)介面幾個額外資訊和額外資料型別
FastAPI 學習之路(十三)Cookie 引數,Header引數
FastAPI 學習之路(十四)回應模型
FastAPI 學習之路(十五)回應狀態碼
FastAPI 學習之路(十六)Form表單
我們去實作下上傳,看一下檔案如何上傳
from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/files/") def create(file: bytes = File(...)): return {"file_size": len(file)} @app.post("/uploadfile/") def upload_file(file: UploadFile = File(...)): return {"filename": file.filename}
我們去測驗下

試下另外一個介面

兩個介面都是可以上傳檔案的,
File 是直接繼承自 Form 的類,
注意,從 fastapi 匯入的 Query、Path、File 等項,實際上是回傳特定類的函式,
UploadFile 的屬性如下:
-
filename:上傳檔案名字串(str),例如, myimage.jpg;
-
content_type:內容型別(MIME 型別 / 媒體型別)字串(str),例如,image/jpeg;
-
file: SpooledTemporaryFile( file-like 物件),其實就是 Python檔案,可直接傳遞給其他預期 file-like 物件的函式或支持庫,
UploadFile 支持以下 async 方法,(使用內部 SpooledTemporaryFile)可呼叫相應的檔案方法,
-
write(data):把 data (str 或 bytes)寫入檔案;
-
read(size):按指定數量的位元組或字符(size (int))讀取檔案內容;
-
seek(offset):移動至檔案 offset (int)位元組處的位置;
-
例如,await myfile.seek(0) 移動到檔案開頭;
-
執行 await myfile.read() 后,需再次讀取已讀取內容時,這種方法特別好用;
-
close():關閉檔案,
因為上述方法都是 async 方法,要搭配「await」使用,
例如,在 async 路徑操作函式 內,要用以下方式讀取檔案內容
contents = await myfile.read()
使用 async 方法時,FastAPI 在執行緒池中執行檔案方法,并 awiat 操作完成,
FastAPI 的 UploadFile 直接繼承自 Starlette 的 UploadFile,但添加了一些必要功能,使之與 Pydantic 及 FastAPI 的其它部件兼容,
我們實作下多個檔案的上傳
from fastapi import FastAPI, File, UploadFile from typing import List app = FastAPI() @app.post("/files/") async def create(fileS: List[bytes] = File(...)): return {"file_sizes": [len(file) for file in fileS]} @app.post("/uploadfile/") async def upload_file(fileS: List[UploadFile] = File(...)): return {"filenames": [file.filename for file in fileS]}
我們看下上傳結果


我們可以針對這些檔案進行處理,
文章首發在公眾號,歡迎關注,

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/320832.html
標籤:Python
