使用boto3在s3中搜索桶

2024-09-29 19:22:43 发布

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

我试图创建一个python脚本,将文件上传到s3存储桶。关键是我希望这个脚本转到s3,搜索所有的bucket,找到一个名称中包含某个关键字的bucket,并将文件上传到该bucket

我目前有:

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。但是,正如您所看到的,我传入的bucket名称必须与s3 bucket完全匹配。我希望能够搜索s3中的所有bucket,并找到包含我传入的关键字的bucket

例如,在本例中,我希望能够传入“myBucke”,并让它在s3中搜索包含它的bucket“myBucket”包含“myBucke”,因此它会将其上载到该文件。这可能吗


Tags: 文件nameimport脚本名称jsondatas3
2条回答

以前的anaswer是有效的,但我最终使用了这个:

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

您可以调用list_bucketsAPI。它“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

一旦有了这个列表,就可以循环检查每个bucket名称,看看它是否与关键字匹配。也许是这样的:

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

相关问题 更多 >

    热门问题