【发布时间】:2021-03-12 04:26:52
【问题描述】:
我使用 AWS S3 作为我的默认文件存储系统。我有一个带有如下文件字段的模型:
class Segmentation(models.Model):
file = models.FileField(...)
我在第二台服务器上运行图像处理作业,将处理后的图像转储到不同的 AWS S3 存储桶。
我想将处理后的图像保存在我的Segmentation 表中。
目前我正在使用 boto3 手动将文件下载到我的“本地”服务器(我的 django-app 所在的位置),然后将其上传到本地 S3 存储桶,如下所示:
from django.core.files import File
import boto3
def save_file(segmentation, foreign_s3_key):
# set foreign bucket
foreign_bucket = 'foreign-bucket'
# create a temp file:
temp_local_file = 'tmp/temp.file'
# use boto3 to download foreign file locally:
s3_client = boto3.client('s3')
s3_client.download_file(foreign_bucket , foreign_s3_key, temp_local_file)
# save file to segmentation:
segmentation.file = File(open(temp_local_file, 'rb'))
segmentation.save()
# delete temp file:
os.remove(temp_local_file)
这工作正常,但它是资源密集型的。我有一些工作需要处理数百张图片。
有没有办法将文件从外部存储桶复制到我的本地存储桶并将segmentation.file字段设置为复制的文件?
【问题讨论】:
-
不确定 - 您能否提供一个如何实施的示例 - 这不会使用同样多的资源吗?
-
在这种情况下,您将节省时间将其保存在磁盘中,然后重新加载它,因为文件对象本身将被流式传输给您。 (尽管需要研究检索将如何发生)。使用文件对象保存和检索它。
-
这能回答你的问题吗? stackoverflow.com/questions/44043036/…
标签: python django amazon-web-services amazon-s3 boto3