如何在 django 中使用键/对象通配符生成 aws 预签名 url

问题描述 投票:0回答:2

我的要求是使用一次生成的预签名 URL 将多个 webm 文件(使用 webrtc 捕获)上传到 s3。

我尝试过下面的代码来生成预签名的网址并使用邮递员上传文件

def create_presigned_url(method_name,s3object,expiration=36000):
    
    try:
        response = s3_client.generate_presigned_post(S3Bucket,
                                                     Key = "",
                                                     Fields=None,
                                                     Conditions = [
                                                                    ["content-length-range",  100, 1000000000],
                                                                    ["starts-with", "$key", "/path-to-file/]
                                                        ],
                                                     ExpiresIn=expiration)
       
    except Exception as e:
        logging.error(e)
        return None
    return response

当我从邮递员处尝试时出现以下错误

enter image description here

django boto3 wildcard pre-signed-url
2个回答
4
投票

预签名 URL 不支持通配符。

我无法找到任何明确说明这一点的文档,但是我今天必须实现相同的目标,而我的发现表明这是不可能的。

我使用 key test/* 创建了一个预签名 URL。
我只能检索 S3 中名为 test/* 的文件的内容,但无法检索任何其他带有 test/ 前缀的文件。对于其他每个文件,请求失败,因为“我们计算的请求签名与您提供的签名不匹配。请检查您的密钥和签名方法。”。

此错误具体指出请求与签名不匹配,这与我对不存在的对象创建签名 url 并且由于找不到密钥而导致请求失败的情况不同。


0
投票

Morras 的答案可能适用于预先签名的 PUT URL。但是使用预先签名的 POST URL,您可以使用

${filename}
的特殊
Key
值,该值采用用户提供的文件名,并允许您对多个文件使用相同的 URL。

response = s3.generate_presigned_post(
    Bucket="mycoolbucket",
    Key="myprefix/${filename}", # Be careful if you're using Python f-strings
    Fields=None,
    Conditions=[
        ["starts-with", "$key", f"/myprefix"],
        ["content-length-range", 0, 10485760],
    ],
    ExpiresIn=(10 * 60),
)

# Example usage
for file_name in ["test.txt", "test2.txt"]:
    with open(file_name, "rb") as f:
        files = {"file": (file_name, f)}
        http_response = requests.post(
            response["url"], data=response["fields"], files=files
        )
        print(http_response)

请参阅:https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/s3/client/generate_presigned_post.html

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.