You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure App Service中Flask应用读取ADLS Gen2 CSV时服务主体认证失败

问题排查与修复方案

1. 代码逻辑修正

你的代码存在几个明确的错误,直接导致认证或文件访问失败:

  • 错误调用容器创建接口:create_file_system(file_system="")传入空字符串会创建无效容器,你应该直接获取已存在的目标容器,而非创建。替换为get_file_system_client并传入实际容器名称。
  • 不必要的文件手动关闭:with语句会自动管理文件句柄,无需调用my_file.close()。
  • App Service路径建议:避免写当前目录,优先使用平台提供的临时目录,防止权限问题。

修正后的核心代码:

from azure.identity import ClientSecretCredential
from azure.storage.filedatalake import DataLakeServiceClient
import os

# 从环境变量读取敏感信息(不要硬编码)
tenant_id = os.getenv("AZURE_TENANT_ID")
client_id = os.getenv("AZURE_CLIENT_ID")
client_secret = os.getenv("AZURE_CLIENT_SECRET")
account_url = "https://xxx.dfs.core.windows.net/"

credential = ClientSecretCredential(tenant_id, client_id, client_secret)
service = DataLakeServiceClient(account_url=account_url, credential=credential)

# 替换为你的实际容器名称
file_system_client = service.get_file_system_client(file_system="your-container-name")
# 文件在根目录则留空,否则填子目录路径
directory_client = file_system_client.get_directory_client("")

file_client = directory_client.get_file_client("File.csv")
download = file_client.download_file()
downloaded_bytes = download.readall()

# 使用App Service临时目录存储文件
temp_file_path = os.path.join(os.getenv("TEMP", "./"), "sample.txt")
with open(temp_file_path, "wb") as my_file:
    my_file.write(downloaded_bytes)

2. 服务主体权限配置

  • 必须给服务主体分配Storage Blob Data Reader角色(而非仅管理类角色),数据操作需要数据平面权限。在Azure门户的存储账户→访问控制(IAM)→添加角色分配,选择该角色并分配给你的服务主体。

3. App Service环境变量配置

  • 不要在代码中硬编码tenant_id、client_id、client_secret,在App Service的配置→应用程序设置中添加这些变量,代码通过os.getenv()读取,避免敏感信息泄露。

4. 存储账户防火墙/网络配置

  • 如果存储账户启用了防火墙,需将App Service的出站IP地址加入存储账户的允许列表,或者将App Service接入虚拟网络并配置存储账户的VNet访问规则。

5. 依赖包版本检查

确保安装的Azure SDK包为最新稳定版,避免版本兼容问题:

pip install --upgrade azure-identity azure-storage-file-datalake

内容的提问来源于stack exchange,提问作者Saurabh Verma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 23:52:44