您如何在put_object中指定标记?

时间:2018-08-01 14:00:26

标签: python python-3.x amazon-web-services amazon-s3 boto3

我需要使用put_object指定标签,如下所示:

s3client = boto3.client('s3')

response = s3client.put_object(Bucket = dest_bucket_name, Body = body, Key = dest_key, Tagging = tagging, ACL = acl )

我的问题是标记变量应使用哪种数据结构?

我看过各种示例,但是我无法使它们正常工作。例如:

tagging = {'TagSet' : [
            {
                'Key': 'voiceid',
                'Value': polly_voice
            },
            {
                'Key': 'author',
                'Value': book_author
            },
            . . .
          ]
     }

给我

 "errorMessage": "Parameter validation failed:\nInvalid type for parameter Tagging, value: {'TagSet': [{'Key': 'voiceid', 'Value': 'Matthew'}, {'Key': 'author', 'Value': 'some guy'},...]}, type: <class 'dict'>, valid types: <class 'str'>"

我看到它需要一个字符串,但是我如何指定key:value对呢?我发现的所有示例都使用了某些特定的数据结构,如示例中所示。

我怀疑这有什么区别,但是我是在lambda函数中完成的。

2 个答案:

答案 0 :(得分:1)

要使其正常工作,请尝试以下代码:

tags = 'voiceid={}&author={}'.format(polly_voice, book_author)
s3client = boto3.client('s3')
response = s3client.put_object(
    Bucket=dest_bucket_name,
    Body=body,
    Key=dest_key,
    Tagging=tags
)

您也可以参考this stackoverflow答案。

答案 1 :(得分:0)

对您的字典进行 URL 编码并使用 this answer

传递结果字符串

对于 Python3:

>>> import urllib.parse
>>> tags = {'key1':'value1','key2':'value2'}
>>> tagging = urllib.parse.urlencode(tags)
>>> print(tagging)
key1=value1&key2=value2