【发布时间】:2020-11-17 16:39:11
【问题描述】:
假设我有一个表单,用户可以在其中提交图像文件,然后我想将它们发布到我的 AWS S3 存储桶。我不想直接使用pre-signed URLs 传递它们,因为我正在压缩/修改图像。
如果我先将它们保存到我的文件系统然后使用 s3_client.upload_file 并从文件系统中获取图像可以吗?
问题是,我在 Heroku 上托管我的网站,它与临时文件系统一起使用,并且在某些时候,图像将从我的静态文件夹中消失。但是,在这种情况下,我将此作为一个优势,因为只有在我完成将图像上传到我的 S3 存储桶时,我才需要文件系统中的图像。这是一个好方法吗?
代码
如果我尝试s3_client.upload_file 而我的文件系统中还没有图像,客户端将抛出错误。
with Image.open(image) as i:
i = Image.open(image)
# If the image is for background, create multiple sizes.
if is_background:
img_1920_1920 = i.resize((1920, 1920), Image.LANCZOS)
img_400_400 = i.resize((800, 533), Image.LANCZOS)
# Add images to s3 bucket
current_app.s3_client.upload_file(safe_filename, current_app.config['AWS_BUCKET_NAME'], os.path.join(image_path, '1920_1920/', safe_filename))
current_app.s3_client.upload_file(safe_filename, current_app.config['AWS_BUCKET_NAME'], os.path.join(image_path, '800_533/', safe_filename))
可能的解决方案
我尝试这样做,但我不知道考虑到这种情况(网站托管在 Heroku 上)是否是一种好习惯。
- 压缩/修改图像并将它们保存到文件系统
- 完成压缩后立即将它们发布到 AWS S3
with Image.open(image) as i:
i = Image.open(image)
# If the image is for background, create multiple sizes.
if is_background:
img_1920_1920 = i.resize((1920, 1920), Image.LANCZOS)
img_400_400 = i.resize((800, 533), Image.LANCZOS)
# Save images in filesystem
img_1920_1920.save( os.path.join(image_path, '1920_1920/', safe_filename), optimize=True, quality=85)
img_400_400.save( os.path.join(image_path, '800_533/', safe_filename), optimize=True, quality=85)
# Add images to s3 bucket
current_app.s3_client.upload_file(os.path.join(image_path, '1920_1920/', safe_filename), current_app.config['AWS_BUCKET_NAME'], os.path.join(image_path, '1920_1920/', safe_filename))
current_app.s3_client.upload_file(os.path.join(image_path, '800_533/', safe_filename), current_app.config['AWS_BUCKET_NAME'], os.path.join(image_path, '800_533/', safe_filename))
【问题讨论】:
标签: python amazon-web-services flask heroku amazon-s3