Skip to main content
 首页 » 编程设计

python之更新 s3 中的元数据

2025年05月04日30lidabo

我使用 Amazon boto v2.38 编写 python 脚本来访问我的 S3 存储桶。

我想更新存储桶中的文件(我知道它在 S3 中称为“key”)。路径是 MyBucket/myfile/demo.txt 。此外,我还想更新名为“name”的元数据。这是我试过的代码:

# connect to key 
conn = boto.connect_s3() 
bucket = conn.get_bucket("MyBucket") 
 
my_key = Key(bucket) 
my_key.key = "myfile/demo.txt" 
 
# if key exists, then update the file & its metadata 
if my_key.exists(): 
   new_meta_data = {"name": "xyz"} 
   # update metadata 
   my_key.copy("MyBucket", my_key.name, new_meta_data, preserve_acl=True) 
   # update file content in S3 by using the local file demo.txt 
   my_key.set_contents_from_filename("demo.txt") 

但是,它不起作用...我没有看到元数据得到更新。为什么?

请您参考如下方法:

您可以只更新 key 的本地元数据,然后执行文件更新:

import boto 
 
conn = boto.connect_s3() 
bucket = conn.get_bucket("MyBucket") 
key = bucket.get_key('myfile/demo.txt') 
key.set_metadata('name', 'xyz') 
key.set_contents_from_filename('demo.txt') 

现在 name 应该作为元数据出现在 S3 中。但是请注意,执行此操作时 ACL 可能会更改。

也可以用 key.set_remote_metadata() 来完成。这不需要您更新 key 的内容(但您可以根据需要更新):

conn = boto.connect_s3() 
bucket = conn.get_bucket('MyBucket') 
key = bucket.get_key('myfile/demo.txt') 
key.set_remote_metadata({'name': 'xyz'}, {}, True)