首页 > 解决方案 > 将 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]}

标签: pythonfastapitemporary-files

解决方案


在此处查看 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

推荐阅读