首页 > 解决方案 > Python configparser 从 S3 读取配置而不下载

问题描述

有没有办法从 s3 读取 .ini 配置文件而不下载它?

我试过的:

配置.ini:

[DEFAULT]
test = test1
test1 = test2

[ME]
me = you
you = he

代码:

import boto3
import io
import configparser

s3_boto = boto3.client('s3')
configuration_file_bucket = "mybucket"
configuration_file_key = "config.ini"
obj = s3_boto.get_object(Bucket=configuration_file_bucket, Key=configuration_file_key)

config = configparser.ConfigParser()
config.read(io.BytesIO(obj['Body'].read()))

它返回 []。

我试图确保

obj['Body'].read()

正在返回一个包含 config.ini 内容的二进制文件。这是有效的。它在更远的地方断裂。

标签: pythonamazon-s3configparser

解决方案


read方法ConfigParser接受一个文件名,但你传递给它一个文件对象。

您可以改为使用该read_string方法,以便您可以将对象的read方法返回的内容传递给它StreamingBody

config.read_string(obj['Body'].read().decode())

推荐阅读