步骤 1) 为 azure 函数启用 azure 身份 (python 3.10) 步骤 2) 复制对象(主体)ID 作为容器设置中的新访问策略 步骤3)尝试运行
def access_another_blob_container():
# Initialize the BlobServiceClient
blob_service_client = BlobServiceClient(
account_url="https://basefunctionstorage.blob.core.windows.net/",
credential=DefaultAzureCredential()
)
# Get the container client
container_client = blob_service_client.get_container_client("complete")
# List all blobs in the container
blob_list = container_client.list_blobs()
blobs = [blob.name for blob in blob_list]
logging.info(f"Blob Names in another container: {blobs}")
# Read the content of a specific blob
blob_client = container_client.get_blob_client("test_file.xlsx")
blob_content = blob_client.download_blob().readall()
logging.info(f"Blob Content in another container: {blob_content.decode('utf-8')}")
这会导致 403 Forbidden: AuthorizationPermissionMismatch 错过步骤的任何建议
我已在此部分下添加具有所有权限的对象 ID:“racwdl”
最佳答案
我创建了一个函数应用并为 Azure Function 启用了托管身份,为此导航至 Settings> Identity> System-assigned> ON> Save
检查如下:
我向存储帐户中的函数应用分配了贡献者角色。
我在容器中上传了一个 test_file.xlsx 文件,如下所示:
代码:
import os
import azure.functions as func
from azure.storage.blob import BlobServiceClient
def main(req: func.HttpRequest, context: func.Context) -> func.HttpResponse:
try:
if 'AzureWebJobsStorage' in os.environ:
storage_connection_string = os.environ['AzureWebJobsStorage']
else:
from azure.identity import DefaultAzureCredential
credential = DefaultAzureCredential()
storage_connection_string = None
blob_service_client = BlobServiceClient.from_connection_string(storage_connection_string)
container_client = blob_service_client.get_container_client("hellopavan")
blob_list = container_client.list_blobs()
blobs = [blob.name for blob in blob_list]
return func.HttpResponse(f"Blob Names in Container: {', '.join(blobs)}", status_code=200)
except Exception as e:
return func.HttpResponse(f"Error: {str(e)}", status_code=500)
要求.txt:
azure-functions
azure-identity
azure-storage-blob
以上代码执行成功。检查如下:
通过输出 URL,我在浏览器中获得了容器中的 blob 名称,如下所示,
输出:
关于python - 使用azure函数标识访问存储容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/77063054/