gpt4 book ai didi

python - AWS boto3 get_object 调用的 IfMatch 参数如何工作?

转载 作者:行者123 更新时间:2023-12-01 07:30:27 27 4
gpt4 key购买 nike

boto3 s3 get_object功能文档(从 AWS 服务定义文件自动生成)将 IfMatch 参数描述为

Return the object only if its entity tag (ETag) is the same as the one specified, otherwise return a 412 (precondition failed).

但是,当我尝试使用 IfMatch 参数时,我无法让 S3 使用非 200 HTTP 状态代码或抛出异常进行响应。

此示例代码

import boto3
import hashlib
import json

BUCKET = 'your-bucket-name-goes-here'
data = {'foo': 'bar', 'baz': 'buz'}
payload = json.dumps(data, sort_keys=True, indent=4).encode('UTF-8')
etag = hashlib.md5(payload).hexdigest()
print("Locally computed etag : {}".format(etag))
client = boto3.client('s3')
response = client.put_object(
Body=payload,
Bucket=BUCKET,
ContentType='application/json',
Key='/test.json')
etag_with_quotes = response['ETag']
print("Etag returned from put_object: {}".format(etag_with_quotes))

response = client.get_object(
Bucket=BUCKET,
Key='/test.json',
IfMatch=etag
)
print("Etag returned from get_object: {}".format(response['ETag']))
print("HTTP status code : {}".format(response['ResponseMetadata']['HTTPStatusCode']))

response = client.get_object(
Bucket=BUCKET,
Key='/test.json',
IfMatch=etag_with_quotes
)
print("Etag returned from get_object: {}".format(response['ETag']))
print("HTTP status code : {}".format(response['ResponseMetadata']['HTTPStatusCode']))

产生此输出

Locally computed etag : d14e36174d57c305bd9d7c171e669ac8
Etag returned from put_object: "d14e36174d57c305bd9d7c171e669ac8"
Etag returned from get_object: "d14e36174d57c305bd9d7c171e669ac8"
HTTP status code : 200
Etag returned from get_object: "d14e36174d57c305bd9d7c171e669ac8"
HTTP status code : 200

如果本地副本相同,如何使用 IfMatch 参数来避免下载文件?

最佳答案

IfMatch 如果 ETag 匹配,则下载对象。要仅下载不同的内容,请使用 IfNoneMatch

<小时/>

另请注意,这仅适用于未使用分段上传上传的对象。分段上传使用 different ETag algorithm包含各个部分的二进制(非十六进制)md5 哈希值的十六进制 md5 哈希值,然后是 -,然后是部分的数量。您可以自己成功计算这些,但比较复杂。

关于python - AWS boto3 get_object 调用的 IfMatch 参数如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57228127/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com