如何在不删除现有标签的情况下使用boto3将标签添加到S3存储桶中?

2024-10-02 14:28:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用此函数:

s3 = boto3.resource('s3')
bucket_tagging = s3.BucketTagging(bucket)
Set_Tag = bucket_tagging.put(Tagging={'TagSet':[{'Key':'Owner', 'Value': owner}]})

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


Tags: key函数s3bucketputtag标签boto3
3条回答

我会用下面的

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})

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

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

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接受的数量]

设置_bucket_标记(“在线选择“,True,key1=“值1”,key2=“value2”,key3=“value3”)

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

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

在函数调用中添加标记:

^{pr2}$

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

相关问题 更多 >