FastAPI 学习之路(四)使用pydantic模型做请求体
FastAPI 学习之路(十三)Cookie 参数,Header参数
前言
我们之前分享的是form表单。这次我们分享的是上传文件
正文
我们去实现下上传,看一下文件如何上传
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/files/")
def create(file: bytes = File(...)):
return {"file_size": len(file)}
@app.post("/uploadfile/")
def upload_file(file: UploadFile = File(...)):
return {"filename": file.filename}
我们去测试下
试下另外一个接口
两个接口都是可以上传文件的。
File 是直接继承自 Form 的类。
注意,从 fastapi 导入的 Query、Path、File 等项,实际上是返回特定类的函数。
UploadFile 的属性如下:
UploadFile 支持以下 async 方法,(使用内部 SpooledTemporaryFile)可调用相应的文件方法。
因为上述方法都是 async 方法,要搭配「await」使用。
例如,在 async 路径操作函数 内,要用以下方式读取文件内容:
contents = await myfile.read()
使用 async 方法时,FastAPI 在线程池中执行文件方法,并 awiat 操作完成。
FastAPI 的 UploadFile 直接继承自 Starlette 的 UploadFile,但添加了一些必要功能,使之与 Pydantic 及 FastAPI 的其它部件兼容。
我们实现下多个文件的上传
from fastapi import FastAPI, File, UploadFile
from typing import List
app = FastAPI()
@app.post("/files/")
async def create(fileS: List[bytes] = File(...)):
return {"file_sizes": [len(file) for file in fileS]}
@app.post("/uploadfile/")
async def upload_file(fileS: List[UploadFile] = File(...)):
return {"filenames": [file.filename for file in fileS]}
我们看下上传结果
我们可以针对这些文件进行处理。
后记
发现问题,解决问题。遇到问题,慢慢解决问题即可。
欢迎关注雷子说测试开发,后续将会持续为大家分享更多的技术知识
如果你有问题可以留言或者加我微信:952943386。2021,一起牛转钱坤,一起牛逼。
如果觉得这篇文章还不错,来个【分享、点赞、在看】三连吧,让更多的人也看到~