首页 > 解决方案 > 相当于通过 Azure Blob 的 S3 预签名 URL 上传文件

问题描述

我一直在尝试将 Web 应用程序从 AWS 迁移到 Azure。我们为用户上传做的一件事是在后端为 S3 生成预​​签名的 URL,前端可以使用这些 URL 通过 POST 请求上传文件。代码看起来像这样:

import boto3

url = boto3.client('s3').generate_presigned_url(
    ClientMethod='put_object', 
    Params={'Bucket': 'BUCKET_NAME', 'Key': 'OBJECT_KEY'},
    ExpiresIn=3600)
return url 

我试图找出 Azure 的 Blob 存储的等价物。从文档中我可以猜到最好的方法是使用 SAS,但这只是返回一个令牌。IE

from azure.storage.blob import ResourceTypes, AccountSasPermissions, generate_account_sas

sas_token = generate_account_sas(
    "accountname",
    "<secret>",
    resource_types=ResourceTypes(object=True),
    permission=AccountSasPermissions(read=True, write=True),
    expiry=datetime.utcnow() + timedelta(hours=1)
)

如何将其转换为可以 POST 文件的 URL?

标签: azureamazon-s3azure-storageazure-blob-storage

解决方案


这实际上非常简单 - 您只需在适当的 URL 前添加一个 SAS URL(相当于 AWS S3 中的预签名 URL),然后执行操作(调用 REST API)。

要对帐户执行操作,您将https://accountname.blob.core.windows.net在 SAS 令牌之前添加。

要对 blob 容器执行操作,您将预先https://accountname.blob.core.windows.net/containername添加到您的 SAS 令牌。

要对 blob 执行操作,您将https://accountname.blob.core.windows.net/containername/blobname在 SAS 令牌之前添加。

更新

这是获取blob_client可执行 blob 相关操作的代码的代码。这利用了Azure Storage Blobs SDK version 12.8.1.

from azure.storage.blob import ResourceTypes, AccountSasPermissions, generate_account_sas,BlobClient
from datetime import datetime,timedelta

account_name = "account-name"
account_key = "account-key=="
container_name = "test"
blob_name = "blobs.txt"
account_url = "https://" + account_name + "blob.core.windows.net"

sas_token = generate_account_sas(
    account_name,
    account_key,
    resource_types=ResourceTypes(object=True),
    permission=AccountSasPermissions(read=True, write=True),
    expiry=datetime.utcnow() + timedelta(hours=1)
)

print(sas_token)

sas_url = account_url + "?" + sas_token

print(sas_url)

blob_client = BlobClient(sas_url, container_name, blob_name)

#...now you can call "upload_blob" method to upload the file.

推荐阅读