【问题标题】:Why are my Amazon S3 key permissions not sticking?为什么我的 Amazon S3 密钥权限没有保留?
【发布时间】:2014-05-22 14:04:45
【问题描述】:

我正在使用 Python 库 boto 连接到 Amazon S3 并为静态网站创建存储桶和密钥。我的键和值是动态生成的,因此我以编程方式而不是通过 Web 界面(它使用 Web 界面工作)来执行此操作。我的代码目前如下所示:

import boto
from boto.s3.connection import S3Connection
from boto.s3.key import Key

conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.create_bucket(BUCKET_NAME)
bucket.configure_website('index.html', 'error.html')
bucket.set_acl('public-read')

for template in ['index.html', 'contact-us.html', 'cart.html', 'checkout.html']:
    k = Key(bucket)
    k.key = key
    k.set_acl('public-read')
    k.set_metadata('Content-Type', 'text/html')
    k.set_contents_from_string(get_page_contents(template))

我在这段代码中遇到了各种错误和问题。当密钥已经存在并且我使用此代码更新它们时,我会将每个密钥的 ACL 设置为 public-read,但在浏览器中查看文件时仍然会收到 403 禁止错误。

我尝试删除所有键以从头开始重新创建它们,现在我得到了 NoSuchKey 异常。显然钥匙不存在,因为我正在尝试创建它。

我是不是走错了路?有没有不同的方法来创建密钥而不是更新它们?当权限不存在时,我是否遇到了某种竞争情况?

【问题讨论】:

  • 你在 python shell 中试过这些例子boto.s3.amazonaws.com/s3_tut.html 吗??
  • 我不确定,但是当您使用已经存在的密钥时应该使用bucket.get_key 吗?

标签: python django amazon-s3 acl boto


【解决方案1】:

我仍然不完全确定为什么上面的代码不起作用,但我发现了一种不同的(或更新的?)用于创建密钥的语法。操作的顺序似乎也有一些影响。这就是我想出的有效方法:

conn = S3Connection(AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY)
bucket = conn.create_bucket(store.domain_name)
bucket.set_acl('public-read')
bucket.configure_website('index.html', 'error.html')

for template in ['index.html', 'contact-us.html', 'cart.html', 'checkout.html']:
    k = bucket.new_key(template)
    k.set_metadata('Content-Type', 'text/html')
    k.set_contents_from_string(get_page_contents(template))
    k.set_acl('public-read') #doing this last seems to be important for some reason

【讨论】:

  • 只是一个小提示:不知道旧的 bo​​to 版本,但在新版本中,“set_metadata()”部分不起作用,因为它只在创建时设置。因此示例中的内容类型将是默认的,即“application/octet-stream”。
【解决方案2】:

这也困扰着我。 boto 的 set_contents_from_string() 方法显然将密钥的 ACL 设置为私有,覆盖任何现有的 ACL。

因此,如果您执行set_acl('public-read'),然后是set_contents_from_string(),则'public-read' 将被覆盖。

【讨论】:

    【解决方案3】:

    我可以通过策略关键字 arg 一次性设置 ACL:

    k.set_contents_from_stream(buff, policy='public-read')
    

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2012-03-05
      • 1970-01-01
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多