FastAPI 教程翻译 - 用户指南 20 - 请求表单和文件

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.

您可以使用 FileForm 同时定义文件和表单字段

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

导入 FileForm

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

定义 FileForm 参数

Create file and form parameters the same way you would for Body or Query:

创建文件和表单参数的方式与使用 BodyQuery 的方式相同:

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 and Form parameters in a path operation, but you can’t also declare Body fields that you expect to receive as JSON, as the request will have the body encoded using multipart/form-data instead of application/json.

您可以在路径操作中声明多个 FileForm 参数,但是不能声明以 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.

当您需要在同一请求中接收数据和文件时,可以同时使用 FileForm

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值