python-3.x - 使用校验和验证通过 Django 从 AWS S3 上传和下载的文件的完整性
问题描述
使用 Django 我正在尝试在 AWS S3 中上传多个文件。文件大小可能从 500 MB 到 2 GB 不等。我需要检查上传和下载文件的完整性。
我已经看到使用 PUT 操作我可以上传最大为 5GB 的单个对象。他们还提供“ContentMD5”选项来验证文件。我的问题是:
- 如果我上传大于 1 GB 的文件,我应该使用 PUT 选项吗?因为生成此类文件的 MD5 校验和可能会超出系统内存。我该如何解决这个问题?或者是否有更好的解决方案可用于此任务?
要下载带有校验和的文件,AWS 有 get_object() 函数。我的问题是:
- 可以用这个功能下载多个文件吗?
- 如何使用它从 S3 下载带有校验和的多个文件?我找了一些例子,但注意到的不多。现在我正在使用以下代码在 Django 中以 zip 格式下载和提供多个文件。我想将文件作为带有校验和的 zip 提供,以验证传输。
s3 = boto3.resource('s3', aws_access_key_id=base.AWS_ACCESS_KEY_ID, aws_secret_access_key=base.AWS_SECRET_ACCESS_KEY)
bucket = s3.Bucket(base.AWS_STORAGE_BUCKET_NAME)
s3_file_path = bucket.objects.filter(Prefix='media/{}/'.format(url.split('/')[-1]))
# set up zip folder
zip_subdir = url.split('/')[-1]
zip_filename = zip_subdir + ".zip"
byte_stream = BytesIO()
zf = ZipFile(byte_stream, "w")
for path in s3_file_path:
s3_url = f"https://%s.s3.%s.amazonaws.com/%s" % (base.AWS_STORAGE_BUCKET_NAME,base.AWS_S3_REGION_NAME,path.key)
file_response = requests.get(s3_url)
if file_response.status_code == 200:
try:
tmp = tempfile.NamedTemporaryFile()
print(tmp.name)
tmp.name = path.key.split('/')[-1]
f1 = open(tmp.name, 'wb')
f1.write(file_response.content)
f1.close()
zip_path = os.path.join('/'.join(path.key.split('/')[1:-1]), tmp.name)
zf.write(tmp.name,zip_path)
finally:
os.remove(tmp.name)
zf.close()
response = HttpResponse(byte_stream.getvalue(), content_type="application/x-zip-compressed")
response['Content-Disposition'] = 'attachment; filename=%s' % zip_filename
我正在学习 AWS S3,这是我第一次使用它。我将不胜感激有关此问题的任何建议。
解决方案
推荐阅读
- sql-server - SSIS IMPORT:Excel 到带有日期列的 sql 服务器(将 unicode 字符串转换为 DT_DBDATE)
- java - 使用 RecyclerView 时如何在同一张卡片下显示名称?
- python - 如何在python中打开加密的Url?
- python - 在 Django 中查询用户
- html - CSS Grid如何将项目推到底部然后向左
- python - Raspberry pi 中的 Crontab Selenium Chromium(未知错误:DevToolsActivePort 文件不存在)
- javascript - React Native Picker 在滚动后移回第一个项目并且不选择正确的值
- python - 这个属性装饰器有什么问题(python)
- c# - PHP 和 C# .NET 的正则表达式模式相同,但输出不同
- sql - cout和group by时如何在laravel中选择关系数据