我一直在尝试将 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/