FastAPI基础之 表单和文件操作

  我们可以使用File同时定义文件和表单字段Form。

  信息

  要接收上载的文件和/或表单数据,请先安装python-multipart。

  例如pip install python-multipart。

  1、导入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,

  }

  2、定义File和Form参数

  创建文件和表单参数,你会为同样的方式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(...)

  ): 枣庄人流医院哪家好 http://mobile.0632-3679999.com/

  return {

  "file_size": len(file),

  "token": token,

  "fileb_content_type": fileb.content_type,

  }

  文件和表单字段将作为表单数据上载,您将收到文件和表单字段。

  您可以将某些文件声明为bytes,另一些声明为UploadFile。

  警告

  我们可以在路径操作中声明多个File和Form参数,但也不能声明希望以JSON形式接收的字段,因为请求的主体将使用而不是进行编码。Bodymultipart/form-dataapplication/json

  这不是FastAPI的限制,它是HTTP协议的一部分。

请使用浏览器的分享功能分享到微信等