python - 无法从 AWS boto3 生成的签名 URL 下载

标签 python amazon-web-services amazon-s3 boto3

我正在尝试将文件上传到现有的 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/

相关文章:

python - Mongodb Replace_one() with upsert = true 抛出重复键错误

python - 正则表达式 '^[abc]+$' 未按预期工作

amazon-web-services - 将 CloudFront 与没有负载均衡器的单个 EC2 实例一起使用

amazon-web-services - Localstack 在 Docker 中启动,但我无法访问

python - 安装 Google Assistant 时,我报错 "...googlesamples.assistant' 是一个包,无法直接执行...”

Python Interactive Interpreter 在 Windows 上总是返回 "Invalid syntax"

javascript - AWS API 使用 Javascript 签署 POST 请求

amazon-web-services - 每个 Lambda 的 AWS Lambda 不同的 IP 地址

javascript - 纯 Javascript 应用 + Amazon S3?

node.js - Amazon S3 403 禁止错误适用于 KML 文件,但不适用于 JPG 文件