首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在不使用S3删除现有标记的情况下向boto3桶添加标记?

如何在不使用S3删除现有标记的情况下向boto3桶添加标记?
EN

Stack Overflow用户
提问于 2018-10-04 11:21:28
回答 3查看 10.5K关注 0票数 5

我正在使用这个函数:

代码语言:javascript
复制
s3 = boto3.resource('s3')
bucket_tagging = s3.BucketTagging(bucket)
Set_Tag = bucket_tagging.put(Tagging={'TagSet':[{'Key':'Owner', 'Value': owner}]})

它正在删除现有的标签,我只能看到一个标签。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-10-04 12:13:35

我将使用以下方法

代码语言:javascript
复制
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})

这将获取现有的标记,添加一个新的标记,然后将它们全部放回。

票数 8
EN

Stack Overflow用户

发布于 2019-05-23 13:25:50

我遇到了同样的问题,并用自己的方法解决了这个问题:

代码语言:javascript
复制
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

然后在函数调用中添加标记:

代码语言:javascript
复制
set_object_keys(....., name="My Name", colour="purple")

这将添加新的标记并更新现有的标记。

票数 5
EN

Stack Overflow用户

发布于 2019-08-07 10:35:51

================桶级标记================

代码语言:javascript
复制
import boto3

session = boto3.session.Session(profile_name='default')
client = session.client('s3', 'ap-southeast-2')

def set_bucket_tags(bucket, update=True, **new_tags):
    old_tags = {}

    if update:
        try:
            old = client.get_bucket_tagging(Bucket=bucket)
            old_tags = {i['Key']: i['Value'] for i in old['TagSet']}
        except Exception as e:
            print(e)
            print("There was no tag")

    new_tags = {**old_tags, **new_tags}

    response = client.put_bucket_tagging(
        Bucket=bucket,
        Tagging={
            'TagSet': [{'Key': str(k), 'Value': str(v)} for k, v in new_tags.items()]
        }
    )

    print(response)

您可以为AWS所接受的任意多个标记。

set_bucket_tags("selim.online",True,key1="value1",key2="value2",key3="value3")

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52645443

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档