请求表单与文件¶
ReadyAPI 支持同时使用 File 和 Form 定义文件和表单字段。
导入 File 与 Form¶
from readyapi import File, Form, ReadyAPI, UploadFile
app = ReadyAPI()
@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,
}
🤓 Other versions and variants
from typing import Annotated
from readyapi import File, Form, ReadyAPI, UploadFile
app = ReadyAPI()
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
from readyapi import File, Form, ReadyAPI, UploadFile
from typing_extensions import Annotated
app = ReadyAPI()
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
定义 File 与 Form 参数¶
创建文件和表单参数的方式与 Body 和 Query 一样:
from readyapi import File, Form, ReadyAPI, UploadFile
app = ReadyAPI()
@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,
}
🤓 Other versions and variants
from typing import Annotated
from readyapi import File, Form, ReadyAPI, UploadFile
app = ReadyAPI()
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
from readyapi import File, Form, ReadyAPI, UploadFile
from typing_extensions import Annotated
app = ReadyAPI()
@app.post("/files/")
async def create_file(
file: Annotated[bytes, File()],
fileb: Annotated[UploadFile, File()],
token: Annotated[str, Form()],
):
return {
"file_size": len(file),
"token": token,
"fileb_content_type": fileb.content_type,
}
文件和表单字段作为表单数据上传与接收。
声明文件可以使用 bytes 或 UploadFile 。
警告
可在一个路径操作中声明多个 File 与 Form 参数,但不能同时声明要接收 JSON 的 Body 字段。因为此时请求体的编码为 multipart/form-data,不是 application/json。
这不是 ReadyAPI 的问题,而是 HTTP 协议的规定。
小结¶
在同一个请求中接收数据和文件时,应同时使用 File 和 Form。