Vercel部署FastAPI文件上传失败:只读文件系统错误求助
解决Vercel部署FastAPI应用时的只读文件系统问题
问题描述
本地运行FastAPI应用时,文件可正常保存至ROOTDIR/sabiduria_tool_api/data/目录,但部署到Vercel后POST端点执行失败,报错如下:
[ERROR] OSError: [Errno 30] Read-only file system: '/var/task/sabiduria_tool_api/data/'
报错触发点位于save_files方法的目录创建步骤,相关代码片段:
async def save_files(self) -> None: if isdir(self.data_store_path): old_files = self.get_files() for o_file in old_files: remove(f"{self.data_store_path}{o_file}") else: mkdir(self.data_store_path) for file in self.files: with open(f"{self.data_store_path}{file.filename}", "wb") as destination: copyfileobj(file.file, destination)
核心原因
Vercel的Serverless函数运行环境为只读文件系统,仅/tmp目录提供临时写入权限,其他路径无法创建或修改文件。
解决步骤
切换至临时目录存储
将文件存储路径改为Vercel允许写入的/tmp目录,例如:# 替换原路径定义 self.data_store_path = "/tmp/sabiduria_tool_api/data/"注意:
/tmp目录内容会在函数调用结束后被清理,仅适用于临时文件处理,无法长期存储数据。改用云存储长期保存
如果需要持久化文件,直接将上传文件发送至云存储服务(如AWS S3、Cloudflare R2等),处理逻辑绕过本地文件存储,全程通过云存储完成读写操作。优化文件操作逻辑
调整目录创建和文件处理代码,确保兼容临时目录:import os from pathlib import Path async def save_files(self) -> None: data_path = Path(self.data_store_path) # 递归创建目录(自动处理父目录不存在的情况) data_path.mkdir(parents=True, exist_ok=True) # 清理目录下旧文件 for old_file in data_path.glob("*"): old_file.unlink() # 写入新文件 for file in self.files: file_path = data_path / file.filename with open(file_path, "wb") as destination: copyfileobj(file.file, destination)
内容的提问来源于stack exchange,提问作者Serdar
相关产品推荐
相关产品推荐

