迁移图片上传功能至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
相关产品推荐
相关产品推荐

