You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

迁移图片上传功能至Zappa任务后AWS部署报错求助

问题原因

AWS Lambda(Zappa基于Lambda运行)的执行环境中,仅/tmp目录拥有读写权限。你的代码直接使用文件名创建/读取文件,会默认尝试操作当前工作目录(该目录为只读),因此触发OSError: [Errno 30] Read-only file system错误。

解决办法

你需要将临时文件的操作路径指定到/tmp目录,以下是两种可行方案:

方案一:手动指定/tmp路径

修改tasks.py中的文件操作逻辑,明确将文件写入/tmp目录:

@task
def upload_photos(photo, name):
    byte_data = photo.encode(encoding='utf-8')
    b = base64.b64decode(byte_data)
    img = Image.open(io.BytesIO(b))
    width = img.width
    height = img.height

    # 拼接/tmp目录下的文件路径
    tmp_file_path = f'/tmp/{name}'
    # 将图片字节数据写入临时文件
    with open(tmp_file_path, 'wb') as file:
        file.write(b)
    # 读取临时文件创建数据库记录
    with open(tmp_file_path, 'rb') as file:
        picture = File(file)
        Images.objects.create(photo=picture, width=width, height=height)
    # 清理临时文件
    os.remove(tmp_file_path)

方案二:使用tempfile模块自动管理临时文件

借助Python的tempfile模块,无需手动拼接路径,它会自动将文件创建在/tmp目录:

import tempfile

@task
def upload_photos(photo, name):
    byte_data = photo.encode(encoding='utf-8')
    b = base64.b64decode(byte_data)
    img = Image.open(io.BytesIO(b))
    width = img.width
    height = img.height

    # 创建临时文件,指定后缀保持原文件格式,delete=False确保文件关闭后不被自动删除
    with tempfile.NamedTemporaryFile(suffix=f'.{name.split(".")[-1]}', delete=False) as tmp_file:
        tmp_file.write(b)
        tmp_file_path = tmp_file.name
    
    try:
        # 读取临时文件创建数据库记录
        with open(tmp_file_path, 'rb') as file:
            picture = File(file)
            Images.objects.create(photo=picture, width=width, height=height)
    finally:
        # 无论是否成功,都清理临时文件
        os.remove(tmp_file_path)

注意:AWS Lambda的/tmp目录最大可用空间为512MB,处理大文件时需留意容量限制。

内容的提问来源于stack exchange,提问作者Anna Berezko

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 15:43:21