azure - 相当于通过 Azure Blob 的 S3 预签名 URL 上传文件

标签 azure amazon-s3 azure-storage azure-blob-storage

我一直在尝试将 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,但这只是返回一个 token 。即

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)
)

如何将其转换为可以将文件发布到的 URL?

最佳答案

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

要对帐户执行操作,您需要将 https://accountname.blob.core.windows.net 添加到您的 SAS token 。

要对 Blob 容器执行操作,您需要将 https://accountname.blob.core.windows.net/containername 添加到您的 SAS token 。

要对 blob 执行操作,您需要将 https://accountname.blob.core.windows.net/containername/blobname 添加到您的 SAS token 。

更新

下面是获取 blob_client 的代码,您可以使用它执行 blob 相关操作。这利用了 Azure Storage Blobs SDK 版本 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.

关于azure - 相当于通过 Azure Blob 的 S3 预签名 URL 上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68156318/

相关文章:

azure - 在Azure机器学习服务Nvidia Compute中导入sentence_transformers时出现段错误

azure - 在 Microsoft Azure 托管的网站上使用 Google Analytics

android - 我如何获得亚马逊多文件上传 s3 android 的进度条

amazon-s3 - 使用 AWS S3 和 Route 53 托管静态网站

azure - 限制将 Blob 上传到 Azure Blob 存储的大小

sql-server - SSMS 18.1 Azure AD 连接选项弹出窗口

azure - 使用 ARM 模板部署多个资源

swift - amazon S3 Swift - 简单的上传需要很长时间,最终没有出现在桶中

azure - 如何使用 terraform 配置 azure 存储生命周期?

c# - 如何获取 Azure Blob 存储中目录的 "Last Modified"属性