首页 > 解决方案 > 使用校验和验证通过 Django 从 AWS S3 上传和下载的文件的完整性

问题描述

使用 Django 我正在尝试在 AWS S3 中上传多个文件。文件大小可能从 500 MB 到 2 GB 不等。我需要检查上传和下载文件的完整性。

我已经看到使用 PUT 操作我可以上传最大为 5GB 的单个对象。他们还提供“ContentMD5”选项来验证文件。我的问题是:

要下载带有校验和的文件,AWS 有 get_object() 函数。我的问题是:

    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,这是我第一次使用它。我将不胜感激有关此问题的任何建议。

标签: python-3.xdjangoamazon-web-servicesamazon-s3

解决方案


推荐阅读