gpt4 book ai didi

python - 如何在 FastAPI 中为 UploadFile 参数选择磁盘位置?

转载 作者:行者123 更新时间:2023-12-05 03:27:49 24 4
gpt4 key购买 nike

我在嵌入式设备上运行 FastAPI 应用程序。嵌入式设备的资源有限(磁盘空间和 RAM)。但是,可以使用空间充足的 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": "解析正文时出错"}

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

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

最佳答案

你可以使用 gettempdir()来自 Python 的 tempfile 的方法模块获取默认临时目录,以及使用.tempdir用于设置/更改用于临时文件的默认目录的变量。

示例:

import tempfile

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

关于python - 如何在 FastAPI 中为 UploadFile 参数选择磁盘位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71374765/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com