【问题标题】:Searching s3 for a bucket using boto3使用 boto3 在 s3 中搜索存储桶
【发布时间】:2021-07-26 03:55:06
【问题描述】:

我正在尝试创建一个将文件上传到 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中的所有bucket,找到包含我传入的关键字的bucket。

例如,在这种情况下,我希望能够传入“myBucke”并让它在 s3 中搜索包含它的存储桶。 'myBucket' 包含 'myBucket',所以它上传到那个。这可能吗?

【问题讨论】:

    标签: python amazon-web-services amazon-s3 boto3 boto


    【解决方案1】:

    您可以调用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
    

    【讨论】:

      【解决方案2】:

      之前的回答有效,但我最终使用了这个:

      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
      

      【讨论】:

        猜你喜欢
        • 2018-08-28
        • 2021-03-29
        • 2021-11-25
        • 2015-09-14
        • 1970-01-01
        • 2018-04-29
        • 1970-01-01
        • 2018-03-29
        • 1970-01-01
        相关资源
        最近更新 更多