azure - 相当于通过 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?
解决方案
这实际上非常简单 - 您只需在适当的 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.
推荐阅读
- javascript - 为什么 replace('_', '-') 在双下划线的情况下不起作用?
- amazon-web-services - 长时间处理 lambda 函数
- c# - Xamarin.Forms 轮播视图
- .net - 连接到 UWP 中的 SignalR(核心)集线器时出现“证书颁发机构无效或不正确”
- python - 如何在 jupyter notebook 中获得大的输出窗口?
- nginx - 友好的 url nginx 修复
- javascript - Chrome 控制台:导航到网页并在加载后单击按钮
- google-cloud-build - 访问 Google Cloud Build 实例上的服务
- android - Android RecyclerView NullPointerException
- c# - Mvc 从级联下拉列表中保存项目