Python 在不知道密钥名称的情况下下载 S3 文件

Python Downloading an S3 file without knowing key name

我正在编写一个 Python 脚本,该脚本 运行 通过 Athena 进行查询,将其输出到 S3 并下载到我的计算机中。我能够通过 Athena 运行 我的查询并将结果输出到 S3。所以我似乎无法弄清楚的下一步是如何在不知道密钥名称的情况下将其下载到我的计算机?

有没有办法在我的 python 脚本输出到 Athena 后查找对象键?
我完成的内容:

# Output location and DB
s3_output = ‘s3_output_here’
database = ‘database_here’

# Function to run Athena query
def run_query(query, database, s3_output):
    while True:
        try:
            response = client.start_query_execution(
                QueryString=query,
                QueryExecutionContext={
                    'Database': database
                    },
                ResultConfiguration={
                    'OutputLocation': s3_output,
                    }
                )
            return response
            break
        except client.exceptions.TooManyRequestsException as e:
            print('Too many requests, trying again after sleep')
            time.sleep(100)

# Our SQL Query    
query = """
SELECT *
FROM test
”””

print("Running query to Athena...")
res = run_query(query, database, s3_output)

我了解如何使用此代码下载文件:

try:
    s3.Bucket(BUCKET_NAME).download_file(KEY, ‘KEY_HERE’)
except botocore.exceptions.ClientError as e:
    if e.response['Error']['Code'] == "404":
        print("The object does not exist.")
    else:
        raise

那么在 运行 完成我的第一个代码后如何读取键名?

您可以使用boto库提供的get_key命令获取密钥。这就是我从 s3 下载内容的方式:

    with open("path/aws-credentials.json") as f:
        data= json.load(f)
        conn = boto.connect_s3(data["accessKeyId"], data["secretAccessKey"])
    bucket = conn.get_bucket('your_bucket')
    file_path = bucket.get_key('path/to/s3/file')
    file_path.get_contents_to_filename('path/on/local/computer/filename')

如果您只是测试一些东西,您可以将您的凭据硬编码到代码中,但如果您打算将其投入生产,最好将您的凭据外部存储在 json 文件之类的文件中。