我正在尝试将文件上传到现有的 AWS s3 存储桶,生成公共(public) URL 并使用该 URL(其他地方)下载该文件。 我正在密切关注example here :
import os
import boto3
import requests
import tempfile
s3 = boto3.client('s3')
with tempfile.NamedTemporaryFile(mode="w", delete=False) as outfile:
outfile.write("dummycontent")
file_name = outfile.name
with open(file_name, mode="r") as outfile:
s3.upload_file(outfile.name, "twistimages", "filekey")
os.unlink(file_name)
url = s3.generate_presigned_url(
ClientMethod='get_object',
Params={
'Bucket': 'twistimages',
'Key': 'filekey'
}
)
response = requests.get(url)
print(response)
我希望从请求库中看到成功返回代码 (200)。
相反,标准输出是:
此外,如果我使用网络浏览器导航到相应的 URL,我会收到一个 XML 文件,其中包含错误代码:InvalidRequest
和错误消息:
The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256.
如何使用 boto3 生成公共(public) URL,任何用户只需导航到相应的 URL 即可轻松下载该 URL,而无需生成复杂的 header ?
为什么官方文档中的示例代码在我的情况下不起作用?
最佳答案
AWS S3 在美国地区仍然支持旧版 v2 签名(2014 年之前)。但在新的AWS区域下,仅允许AWS4-HMAC-SHA256(s3v4)。
要支持此功能,您必须在 .aws/config 文件中或在 boto3.s3 资源/客户端实例化期间显式指定它们。例如
# add this entry under ~/.aws/config
[default]
s3.signature_version = s3v4
[other profile]
s3.signature_version = s3v4
或者显式声明它们
s3client = boto3.client('s3', config= boto3.session.Config(signature_version='s3v4'))
s3resource = boto3.resource('s3', config= boto3.session.Config(signature_version='s3v4'))
关于python - 无法从 AWS boto3 生成的签名 URL 下载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47632662/