gpt4 book ai didi

python - 在 AWS 中标记 s3

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

我正在尝试使用 boto3 创建一些 s3 存储桶和对象,然后添加一些标签(对象标记)。然后,我想使用 IAM 通过这些标签来控制对这些对象的访问。我无法找到正确的语法。我使用 create_buckets.py (创建存储桶和对象),然后使用 list_objects.py 列出它们。

如果有人可以帮助我使用向对象和存储桶添加多个标签的语法,我真的很感激。

create_buckets.py

import boto3
from random import randint
import json
session = boto3.session.Session()
s3 = boto3.resource('s3')
state=["Alabama","Alaska","Arizona","Arkansas","California","Colorado","Connecticut"]
for x in state:
bucket_name = x.lower() + '-season-' + str(randint(0, 10000))
s3.create_bucket(Bucket=bucket_name)
for bucket in s3.buckets.all():
print(bucket.name)
s3.Object(bucket.name,'hello.txt').put(Body=open('/tmp/hello.txt','rb'))
copy_source={ 'Bucket':bucket.name,'Key':'hello123.txt'}

list_objects.py

import boto3
s3 = boto3.resource('s3')
for bucket in s3.buckets.all():
print(bucket.name)
for obj in bucket.objects.all():
print(' ' + obj.key)

最佳答案

上传对象时不能定义标签。这是我在上传过程中尝试设置标签时得到的结果。

enter image description here

does not appear to be a valid way to specify a tag.

但是还有办法,

上传对象,上传对象后设置标签。这是完整的工作示例

import logging
import boto3
from botocore.exceptions import ClientError
client = boto3.client('s3')


def upload_file(file_name, bucket, object_name=None):
"""Upload a file to an S3 bucket

:param file_name: File to upload
:param bucket: Bucket to upload to
:param object_name: S3 object name. If not specified then file_name is used
:return: True if file was uploaded, else False
"""
# If S3 object_name was not specified, use file_name
if object_name is None:
object_name = file_name

# Upload the file
s3_client = boto3.client('s3')
try:
response = s3_client.upload_file(file_name, bucket, object_name)
except ClientError as e:
logging.error(e)
return False
return True
s3 = boto3.client('s3')
with open("./test.txt", "rb") as f:

s3.upload_fileobj(f, "config-bucket-name", "test.txt",
ExtraArgs={
'Metadata': {'mykey': 'myvalue'}
})


# set tag once object upload to s3
response = client.put_object_tagging(
Bucket='config-bucket-name',
Key='test.txt',
Tagging={
'TagSet': [
{
'Key': 'ENV',
'Value': 'Prod'
},
{
'Key': 'type',
'Value': 'txt'
}
]
}
)

enter image description here

关于python - 在 AWS 中标记 s3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57016838/

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