如何解决使用 boto3 在 s3 中搜索存储桶
我正在尝试创建一个将文件上传到 s3 存储桶的 Python 脚本。问题是我希望这个脚本转到 s3 并搜索所有存储桶并找到名称中包含某个关键字的存储桶并将文件上传到该存储桶。
我目前有这个:
import boto3
import json
BUCKET_NAME = 'myBucket'
with open('my-file.json','rb') as json_file:
data = json.load(json_file)
s3 = boto3.resource('s3')
s3.Bucket(BUCKET_NAME).put_object(Key='banner-message.json',Body=json.dumps(data))
print ("File successfully uploaded.")
此脚本成功将文件上传到 s3。但是,如您所见,我传入的存储桶名称必须与 s3 存储桶完全匹配。我希望能够搜索 s3 中的所有存储桶并找到包含我传入的关键字的存储桶。
例如,在这种情况下,我希望能够传入 'myBucke' 并让它在 s3 中搜索包含它的存储桶。 'myBucket' 包含 'myBucke',所以它上传到那个。这可能吗?
解决方法
您可以调用 list_buckets
API。它“Returns a list of all buckets owned by the authenticated sender of the request.
”
https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3.html#S3.Client.list_buckets
获得列表后,您可以遍历它以检查每个存储桶名称以查看它是否与关键字匹配。也许是这样的:
s3_client = boto3.client('s3')
buckets = s3_client.list_buckets()['Buckets']
for bucket in buckets:
bucket_name = bucket['Name']
if 'keyword' in bucket_name:
# do your logic to upload
,
以前的答案有效,但我最终使用了这个:
def findBucket(s3):
for bucket in s3.buckets.all():
if('myKeyWord' in bucket.name):
return bucket.name
return 'notFound'
s3 = boto3.resource('s3')
bucketName = findBucket(s3)
if(bucketName != 'notFound'):
#upload file to that bucket
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。