如何select FastAPI 中UploadFile 参数的磁盘位置?

How to select the disk location for UploadFile parameter in FastAPI?

我是运行 嵌入式设备上的FastAPI 应用程序。嵌入式设备资源有限(磁盘 space 和 RAM)。但是,可以使用带有大量 space 的 SD 卡。我想上传一个大文件并将其存储在 SD 卡上。 FastAPI documentation 建议使用 UploadFile 参数。

我尝试了一个简单的应用程序:

from fastapi import FastAPI, File, UploadFile

app = FastAPI()


@app.post("/uploadfile/")
async def create_upload_file(file: UploadFile = File(...)):
    return {"filename": file.filename}

... 发布一个大文件后,我收到状态码 400 和正文的回复 {"detail": "There was an error parsing the body"}.

我在上传过程中监控磁盘使用情况,我看到分区 /tmp 上的空闲 space 正在减少,直到 运行 超出 space。我假设 FastAPI 发现上传的文件太大而无法存储在内存中并决定将其存储在磁盘上。不幸的是,selected 磁盘也太小了。

如何select FastAPI 内部用来存储上传文件的位置?

您可以将以下内容添加到您的应用程序以更改 temp 文件的默认位置(使用 Python 的 tempfile 模块):

import tempfile

tempfile.tempdir = "path/to/tempdir/here"
print("Temp directory after change:", tempfile.gettempdir())