python - 将 fastAPI UploadFile 与接受类文件对象的库一起使用
问题描述
我想知道在上传文件时访问底层文件对象的最佳实践fastAPI
。
使用 fastapi 上传文件时,我们得到的对象是一个starlette.datastructures.UploadFile
. 我们可以访问底层file
属性 a tempfile.SpooledTemporaryFile
。然后我们可以访问底层的私有_file
属性,并将其传递给需要类文件对象的库。
python-docx
下面是使用和的两条路线的示例pdftotext
:
@router.post("/open-docx")
async def open_docx(upload_file: UploadFile = File(...)):
mydoc = docx.Document(upload_file.file._file) #
# do something
@router.post("/open-pdf")
async def open_pdf(upload_file: UploadFile = File(...)):
mypdf = pdftotext.PDF(upload_file.file._file)
# do something
但是,我不喜欢访问私有_file
属性的想法。有没有更好的方法来传递文件对象而不先保存它?
注意:要重现上面的示例,请将以下代码放入launch.py
并运行uvicorn launch:app --reload
:
import docx
import pdftotext
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/open-docx")
async def open_docx(upload_file: UploadFile = File(...)):
mydoc = docx.Document(upload_file.file._file)
# do something
return {"firstparagraph": mydoc.paragraphs[0].text}
@app.post("/open-pdf")
async def open_pdf(upload_file: UploadFile = File(...)):
mypdf = pdftotext.PDF(upload_file.file._file)
# do something
return {"firstpage": mypdf[0]}
解决方案
在此处查看 UploadFile 的文档: https ://fastapi.tiangolo.com/tutorial/request-files/#uploadfile
它说它有一个名为的属性
file: A SpooledTemporaryFile (a file-like object).
This is the actual Python file that you can pass directly to
other functions or libraries that expect a "file-like" object.
所以你不需要访问私有 ._file 属性。只要通过
upload_file.file
推荐阅读
- list - 递归函数 - 反向遍历 List
- c# - VS 扩展中的 .net 标准库找不到它的依赖项
- hadoop - 将 Hive 外部表列名称更改为大写并添加新列
- laravel - 使用 Laravel 发送邮件
- arrays - 优化 4D 张量旋转
- java - 参数索引超出范围 (0 < 1)
- prolog - Prolog:使用附加约束安排开始时间
- javascript - 如何让 VS Code Intellisense 识别 JSDoc 注解?
- typescript - 使用打字稿获取羽毛聊天教程的错误消息“错误:必须向'users.get'方法提供一个ID”
- vue.js - Vue-CLI 和 Visual Studio Code 格式冲突