Trouble setting cache-cotrol header for Amazon S3 key using boto

只谈情不闲聊 提交于 2019-12-05 17:22:06

Use ASCII string as values solves this for me.

AWS_HEADERS = {'Cache-Control': str('public, max-age=15552000')}

If you want to add cache control while uploading the file....

 headers = {
    'Cache-Control':'max-age=604800', # 60 x 60 x 24 x 7 = 1 week
    'Content-Type':content_type,
  }

  k = Key(self.get_bucket())
  k.key = filename
  k.set_contents_from_string(contents.getvalue(), headers)
  if self.public: k.make_public()

If you want to add cache control to existing files...

for key in bucket.list():
  print key.name.encode('utf-8')
  metadata = key.metadata
  metadata['Cache-Control'] = 'max-age=604800' # 60 x 60 x 24 x 7 = 1 week
  key.copy(AWS_BUCKET, key, metadata=metadata, preserve_acl=True)

This is tested in boto 2.32 - 2.40.

cache_control is a property of key, not part of metadata.

So to set cache-control for all the objects in a bucket, you can do this:

s3_conn = S3Connection(AWS_KEY, AWS_SECRET)

bucket = s3_conn.get_bucket(AWS_BUCKET_NAME)

bucket.make_public()

for key in bucket.list():
    key = bucket.get_key(key.name)
    key.cache_control = 'max-age=%d, public' % (3600 * 24 * 360 * 2)
    print key.name + ' ' +  key.cache_control
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!