系列文章:

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

   我们去看下接口请求试试。

FastAPI 学习之路(十八)表单与文件

 

 

 声明文件可以使用 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],
    }

我们看下测试结果

FastAPI 学习之路(十八)表单与文件

 

 FastAPI 学习之路(十八)表单与文件

 

 多个文件上传也是可以的,也是简单的。

文章首发在公众号,欢迎关注。

FastAPI 学习之路(十八)表单与文件

相关文章:

  • 2021-10-24
  • 2021-12-04
  • 2021-06-30
  • 2021-07-26
  • 2022-01-21
  • 2022-02-19
  • 2021-11-28
  • 2021-10-26
猜你喜欢
  • 2021-12-28
  • 2022-01-18
  • 2021-12-02
  • 2022-01-01
  • 2022-02-13
  • 2021-12-15
  • 2022-01-22
相关资源
相似解决方案