【发布时间】:2021-10-01 10:32:52
【问题描述】:
我想知道在使用fastAPI 上传文件时访问底层文件对象的最佳做法。
使用fastapi上传文件时,我们得到的对象是starlette.datastructures.UploadFile。
我们可以访问底层的file 属性,即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.file本身就是类文件对象 -
我怀疑这可能是与 SpooledTemporaryFile 的实现有关的问题:stackoverflow.com/questions/47160211/…
标签: python fastapi temporary-files