使用 boto3 在 s3 中搜索桶
Searching s3 for a bucket using boto3
我正在尝试创建一个 python 脚本来将文件上传到 s3 存储桶。问题是我希望这个脚本转到 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
我正在尝试创建一个 python 脚本来将文件上传到 s3 存储桶。问题是我希望这个脚本转到 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