FastAPI 學習之路(十八)表單與文件


系列文章:

  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],
    }

我們看下測試結果

 

 

 

 多個文件上傳也是可以的,也是簡單的。

文章首發在公眾號,歡迎關注。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM