如何使用 Content-MD5 将对象放入 s3

Mes*_*kov 11 python amazon-s3 amazon-web-services boto3

我尝试使用 boto3 将 XML 文件上传到 S3。按照亚马逊的建议,我想发送数据的 Base64 编码 MD5-128 位摘要(Content-MD5)。

https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectPUT.html https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Object 。放

我的代码:

with open(file, 'rb') as tempfile:
   body = tempfile.read()
tempfile.close()

hash_object = hashlib.md5(body)
base64_md5 = base64.encodebytes(hash_object.digest())

response = s3.Object(self.bucket, self.key + file).put(
            Body=body.decode(self.encoding),
            ACL='private',
            Metadata=metadata,
            ContentType=self.content_type,
            ContentEncoding=self.encoding,
            ContentMD5=str(base64_md5)
        )
Run Code Online (Sandbox Code Playgroud)

当我尝试这个时 str(base64_md5) 创建一个像 'b'ZpL06Osuws3qFQJ8ktdBOw==\n'' 的字符串

在这种情况下,我收到此错误消息:

An error occurred (InvalidDigest) when calling the PutObject operation: The Content-MD5 you specified was invalid.

出于测试目的,我只复制了前面没有 'b' 的值:'ZpL06Osuws3qFQJ8ktdBOw==\n'

然后我收到此错误消息:

botocore.exceptions.HTTPClientError: An HTTP Client raised and unhandled exception: Invalid header value b'hvUe19qHj7rMbwOWVPEv6Q==\n'

任何人都可以帮助我如何将上传文件保存到 S3?

谢谢,

奥利弗

ted*_*r42 9

从@Isaac Fife 的示例开始,将其剥离以识别需要和不需要的内容,并包含导入等以使其成为完全可重现的示例:

(您需要进行的唯一更改是使用您自己的存储桶名称)

import base64
import hashlib
import boto3

contents = "hello world!"
md = hashlib.md5(contents.encode('utf-8')).digest()
contents_md5 = base64.b64encode(md).decode('utf-8')

boto3.client('s3').put_object(
  Bucket="mybucket",
  Key="test",
  Body=contents,
  ContentMD5=contents_md5
)
Run Code Online (Sandbox Code Playgroud)

学习:首先,您尝试生成的 MD5 与“上传”返回的内容不同。我们实际上需要一个 base64 版本,它返回一个 md.hexdigest() 版本。十六进制是base16,而不是base64。

  • 这在 python lambda 中对我有用。我很高兴不需要花时间弄清楚发生了什么(感谢@Isaac)并且有一个干净的可重现示例(感谢@tedder42!) (2认同)
  • 如果您的内容已经是二进制的(因为 OP 打开文件“rb”),只需删除第 6 行“md”赋值语句的 .encode('utf-8') 部分即可。 (2认同)

Isa*_*ife 7

(Python 3.7)

我花了几个小时才弄清楚这一点,因为您得到的唯一错误是“您指定的 Content-MD5 无效”。对调试非常有用......无论如何,这是我用来在重构之前实际让文件正确上传的代码。

json_results = json_converter.convert_to_json(result)
json_results_utf8 = json_results.encode('utf-8')
content_md5 = md5.get_content_md5(json_results_utf8)
content_md5_string = content_md5.decode('utf-8')
metadata = {
    "md5chksum": content_md5_string
}
s3 = boto3.resource('s3', config=Config(signature_version='s3v4'))
obj = s3.Object(bucket, 'filename.json')
obj.put(
    Body=json_results_utf8,
    ContentMD5=content_md5_string,
    ServerSideEncryption='aws:kms',
    Metadata=metadata,
    SSEKMSKeyId=key_id)
Run Code Online (Sandbox Code Playgroud)

和散列

def get_content_md5(data):
    digest = hashlib.md5(data).digest()
    return base64.b64encode(digest)
Run Code Online (Sandbox Code Playgroud)

对我来说,最困难的部分是弄清楚在这个过程的每个步骤中你需要什么编码,而且当时不太熟悉字符串在 python 中的存储方式。

get_content_md5只接受一个 utf-8 字节的对象,并返回相同的对象。但是要将 md5 哈希传递给 aws,它需要是一个字符串。您必须先对其进行解码,然后再将其提供给ContentMD5.

专业提示 -Body另一方面,需要给定字节或可查找对象。seek(0)在将文件传递给 AWS 之前,请确保您将其传递到文件开头的可查找对象,否则 MD5 将不匹配。出于这个原因,使用字节不太容易出错,imo。