[英]Searching s3 for a bucket using boto3
我正在尝试创建一个将文件上传到 s3 存储桶的 python 脚本。 问题是我希望这个脚本到 go 到 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' 包含 'myBucket',所以它上传到那个。 这可能吗?
您可以调用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.