简体   繁体   English

使用 boto3 在 s3 中搜索存储桶

[英]Searching s3 for a bucket using boto3

I'm trying to create a python script that uploads a file to an s3 bucket.我正在尝试创建一个将文件上传到 s3 存储桶的 python 脚本。 The catch is that I want this script to go to s3 and search through all the buckets and find a bucket that contains a certain keyword in its name and upload the file to that bucket.问题是我希望这个脚本到 go 到 s3 并搜索所有存储桶并找到一个名称中包含某个关键字的存储桶并将文件上传到该存储桶。

I currently have this:我目前有这个:

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.") 

This script successfully uploads the file to s3.此脚本成功将文件上传到 s3。 But, as you can see, the bucket name I pass in has to be the same exact match as the s3 bucket.但是,如您所见,我传入的存储桶名称必须与 s3 存储桶完全匹配。 I want to be able to search through all the buckets in s3 and find the bucket that contains the keyword I pass in.我希望能够搜索 s3 中的所有存储桶,找到包含我传入的关键字的存储桶。

For example, in this case, I want to be able to pass in 'myBucke' and have it search s3 for a bucket that contain that.例如,在这种情况下,我希望能够传入“myBucke”并让它在 s3 中搜索包含它的存储桶。 'myBucket' contains 'myBucke', so it uploads it to that. 'myBucket' 包含 'myBucket',所以它上传到那个。 Is this possible?这可能吗?

You can call the list_buckets API.您可以调用list_buckets API。 It " 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它“ 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

Once you have the list, you can loop through it to check each bucket name to see if it matches the keyword.获得列表后,您可以遍历它以检查每个存储桶名称以查看它是否与关键字匹配。 Perhaps something like this:也许是这样的:

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

The previous anaswer works but I ended up using this:以前的回答有效,但我最终使用了这个:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM