FastAPI 教程翻译 - 用户指南 20 - 请求表单和文件
FastAPI Tutorial - User Guide - Request Forms and Files
You can define files and form fields at the same time using File
and Form
.
您可以使用 File
和 Form
同时定义文件和表单字段
Info
信息
To receive uploaded files and/or form data, first install
python-multipart
.要接收上传的文件和 / 或表单数据,请首先安装
python-multipart
。E.g.
pip install python-multipart
.例如:
pip install python-multipart
。
Import File
and Form
导入 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,
}
Define File
and Form
parameters
定义 File
和 Form
参数
Create file and form parameters the same way you would for Body
or Query
:
创建文件和表单参数的方式与使用 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,
}
The files and form fields will be uploaded as form data and you will receive the files and form fields.
文件和表单字段将作为表单数据上载,您将收到文件和表单字段。
And you can declare some of the files as bytes
and some as UploadFile
.
您可以将某些文件声明为 bytes
,而另一些声明为 UploadFile
。
Warning
警告
You can declare multiple
File
andForm
parameters in a path operation, but you can’t also declareBody
fields that you expect to receive as JSON, as the request will have the body encoded usingmultipart/form-data
instead ofapplication/json
.您可以在路径操作中声明多个
File
和Form
参数,但是不能声明以 JSON 形式接收的Body
字段,因为请求的主体将使用multipart/form-data
进行编码而不是application/json
。This is not a limitation of FastAPI, it’s part of the HTTP protocol.
这不是 FastAPI 的限制,它是 HTTP 协议的一部分。
Recap
回顾
Use File
and Form
together when you need to receive data and files in the same request.
当您需要在同一请求中接收数据和文件时,可以同时使用 File
和 Form
。