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

标签 python fastapi

我在嵌入式设备上运行 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/

相关文章:

python - 交错不同长度的列表,消除重复,并保持顺序

docker - docker-compose 中的快速 api 和 nginx 显示 connect() 失败(111 : Connection refused) while connecting to upstream, 客户端 : 172. 27.0.1,服务器:

python - 将 csv 文件发送到 fastAPI 并取回新文件

python - 如何将组装字段添加到 Pydantic 模型

python - 如何将 FastAPI UploadFile(zip 文件)以 .zip 格式保存到磁盘?

python - 从 FastAPI 中发布的 Pydantic 模型更新 SQLAlchemy ORM 现有模型?

python - 如何使用 python 调用 c++ 函数

python - 如何展平 Pandascore E-Sports GET 响应格式的 JSON 数据,以便在 pandas 中拥有非常干净的数据框?

python multiprocessing - 进程终止时运行逻辑

python - 在 Jupyter Notebook 中读取一个巨大的 .csv 文件