新聞中心
FastAPI 支持同時(shí)使用 File 和 Form 定義文件和表單字段。

“只有客戶發(fā)展了,才有我們的生存與發(fā)展!”這是創(chuàng)新互聯(lián)公司的服務(wù)宗旨!把網(wǎng)站當(dāng)作互聯(lián)網(wǎng)產(chǎn)品,產(chǎn)品思維更注重全局思維、需求分析和迭代思維,在網(wǎng)站建設(shè)中就是為了建設(shè)一個(gè)不僅審美在線,而且實(shí)用性極高的網(wǎng)站。創(chuàng)新互聯(lián)對(duì)網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、網(wǎng)站制作、網(wǎng)站開發(fā)、網(wǎng)頁設(shè)計(jì)、網(wǎng)站優(yōu)化、網(wǎng)絡(luò)推廣、探索永無止境。
說明
接收上傳文件或表單數(shù)據(jù),要預(yù)先安裝 python-multipart。
例如,pip install python-multipart。
導(dǎo)入 File 與 Form
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: bytes = File(...), fileb: UploadFile = File(...), token: str = Form(...)
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
定義 File 與 Form 參數(shù)
創(chuàng)建文件和表單參數(shù)的方式與 Body 和 Query 一樣:
from fastapi import FastAPI, File, Form, UploadFile
app = FastAPI()
@app.post("/files/")
async def create_file(
file: bytes = File(...), fileb: UploadFile = File(...), token: str = Form(...)
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
文件和表單字段作為表單數(shù)據(jù)上傳與接收。
聲明文件可以使用 bytes 或 UploadFile 。
警告
可在一個(gè)路徑操作中聲明多個(gè) File 與 Form 參數(shù),但不能同時(shí)聲明要接收 JSON 的 Body 字段。因?yàn)榇藭r(shí)請(qǐng)求體的編碼為 multipart/form-data,不是 application/json。
這不是 FastAPI 的問題,而是 HTTP 協(xié)議的規(guī)定。
小結(jié)
在同一個(gè)請(qǐng)求中接收數(shù)據(jù)和文件時(shí),應(yīng)同時(shí)使用 File 和 Form。
當(dāng)前文章:創(chuàng)新互聯(lián)FastAPI教程:FastAPI教程請(qǐng)求表單與文件
文章來源:http://www.fisionsoft.com.cn/article/djpjiig.html


咨詢
建站咨詢
