嗨,我正在使用boto将文件写入S3存储桶。我最近删除了一个EC2实例,并用新的密钥对启动了一个新实例。我现在可以从bucket中读取文件,但当我尝试写入文件时,它失败了,没有任何错误。我能看到桶里的文件。这是代码:
conn = S3Connection()
bucket = conn.get_bucket('my-bucket')
keylist = bucket.list()
k = Key(bucket)
def upload_file():
# Get the name of the uploaded files
uploaded_files = request.files.getlist("file[]")
current_date = time.strftime("%x").split("/")[0]+time.strftime("%x").split("/")[1]+time.strftime("%x").split("/")[2]
filenames = []
for file in uploaded_files:
# Check if the file is one of the allowed types/extensions
if file and allowed_file(file.filename):
# Make the filename safe, remove unsupported chars
filename = secure_filename(file.filename)
file_contents = file.read()
k.key = current_date + "/" + file.filename
print "uploading files now "
k.set_contents_from_string(file_contents)
我不确定这是否是因为新的钥匙对。不过,它确实提供了读取访问。但写作并没有发生。是因为新实例吗?仅供参考,它在本地主机上运行良好。
IMHO,"它在localhost中完美工作"显示了所犯的错误。
事实上:对于S3连接,除非您定义了无密码策略以允许特定主机写入数据,否则显而易见的方法是使用IAM凭据连接到S3。因此,在您的本地机器中,它会起作用,因为boto3只需从您的aws访问文件夹中获取凭据和配置。
现在你有两个选择。
-
肮脏的方式:创建另一个只对S3有写权限的IAM用户,将其设置在承载应用程序的EC2实例上
-
配置S3存储桶策略,添加从EC2实例IP地址写入的限制。因为VPC内部的EC2可以通过端点直接连接到S3。请在此处查看Bucket策略设置:http://docs.aws.amazon.com/AmazonS3/latest/dev/using-iam-policies.html