New*_*ork 3 python amazon-s3 amazon-web-services boto3 s3-bucket
我正在使用这个功能:
s3 = boto3.resource('s3')
bucket_tagging = s3.BucketTagging(bucket)
Set_Tag = bucket_tagging.put(Tagging={'TagSet':[{'Key':'Owner', 'Value': owner}]})
Run Code Online (Sandbox Code Playgroud)
它正在删除现有标签,我只能看到一个标签。
我会使用以下
s3 = boto3.resource('s3')
bucket_tagging = s3.BucketTagging('bucket_name')
tags = bucket_tagging.tag_set
tags.append({'Key':'Owner', 'Value': owner})
Set_Tag = bucket_tagging.put(Tagging={'TagSet':tags})
Run Code Online (Sandbox Code Playgroud)
这将获取现有标签,添加一个新标签,然后将它们全部放回原处。
我遇到了同样的问题并用我自己的方法解决了它:
import boto3
def set_object_keys(bucket, key, update=True, **new_tags):
"""
Add/Update/Overwrite tags to AWS S3 Object
:param bucket_key: Name of the S3 Bucket
:param update: If True: appends new tags else overwrites all tags with **kwargs
:param new_tags: A dictionary of key:value pairs
:return: True if successful
"""
# I prefer to have this var outside of the method. Added for completeness
client = boto3.client('s3')
old_tags = {}
if update:
old = client.get_object_tagging(
Bucket=bucket,
Key=key,
)
old_tags = {i['Key']: i['Value'] for i in old['TagSet']}
new_tags = {**old_tags, **new_tags}
response = client.put_object_tagging(
Bucket=bucket,
Key=key,
Tagging={
'TagSet': [{'Key': str(k), 'Value': str(v)} for k, v in new_tags.items()]
}
)
return response['ResponseMetadata']['HTTPStatusCode'] == 200
Run Code Online (Sandbox Code Playgroud)
然后在函数调用中添加标签:
set_object_keys(....., name="My Name", colour="purple")
Run Code Online (Sandbox Code Playgroud)
这将添加新标签并更新现有标签
| 归档时间: |
|
| 查看次数: |
7005 次 |
| 最近记录: |