【问题标题】:boto s3 write doesnt work but read file worksboto s3 写入不起作用,但读取文件有效
【发布时间】:2016-03-31 22:10:32
【问题描述】:

您好,我正在使用 boto 将文件写入 S3 存储桶。我最近删除了一个 EC2 实例并使用新的密钥对启动了一个新实例。我现在可以从存储桶中读取文件,但是当我尝试写入文件时,它会失败且没有错误。我可以看到存储桶中的文件。这是代码:

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)

我不确定这是否是因为新的密钥对。不过,它确实提供了读取访问权限。但是写入不会发生。是因为新实例吗?仅供参考,它在 localhost 中完美运行。

【问题讨论】:

  • “它在 localhost 中完美运行”是什么意思?密钥对用于登录 EC2 实例,它们不用于 API 调用。而是检查分配给实例的角色,该角色用于将 IAM 凭证分配给在实例上运行的软件。
  • 您是否从k.set_contents_from_string() 调用中获得了返回值?您可能想尝试为每个单独的文件获取一个新密钥 (k = Key(bucket)),而不是重新使用现有值。

标签: amazon-s3 boto


【解决方案1】:

恕我直言,“它在 localhost 中完美运行”显示了所犯的错误。

事实上: 对于 S3 连接,除非您定义无密码策略以允许特定主机写入数据,否则显而易见的方法是使用您的 IAM 凭证连接到 S3。因此,在您的本地机器上,它可以工作,因为 boto3 只是从您的 aws 访问文件夹中获取凭证和配置。

现在你有两个选择。

  1. 肮脏的方式:创建另一个仅有权写入 S3 的 IAM 用户,将其设置在托管应用程序的 EC2 实例上

  2. 配置您的 S3 存储桶策略,添加限制以从您的 EC2 实例 IP 地址写入。因为 VPC 内部的 EC2 可以通过端点直接连接到 S3。在此处查看存储桶策略设置:http://docs.aws.amazon.com/AmazonS3/latest/dev/using-iam-policies.html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-07
    • 2014-12-12
    • 2015-07-16
    • 1970-01-01
    相关资源
    最近更新 更多