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

使用Azure Python SDK的MetricsQueryClient遇HTTPS不安全请求警告的解决方法

解决Azure Python SDK的InsecureRequestWarning问题

问题场景

我编写了一个Python脚本用于查看存储账户的交易数,代码如下:

cred = DefaultAzureCredential()    
client_metrics = MetricsQueryClient(cred)

#返回过去30天的每日交易数时间序列数据
response = client_metrics.query_resource(
    resource_id,
    metric_names=["Transactions"],
    timespan=timedelta(days=30),
    granularity=timedelta(days=1),
    aggregations=[MetricAggregationType.TOTAL]
)

运行脚本时(使用|& tee -a output.txt收集标准输出和错误输出),在本地VS Code(Windows)和GitHub Actions(使用OIDC)环境下均收到以下警告:

/opt/hostedtoolcache/Python/3.10.13/x64/lib/python3.10/site-packages/urllib3/connectionpool.py:1103: InsecureRequestWarning: Unverified HTTPS request is being made to host 'management.azure.com'. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#tls-warnings
warnings.warn(

解决方案

这个警告是因为Python环境缺少验证Azure服务所需的可信根CA证书,导致HTTPS请求跳过了证书验证环节,存在安全风险。以下是针对不同环境的解决方法:

1. 本地Windows(VS Code)环境

  • 升级或安装certifi包(Python的可信CA证书库):
    pip install --upgrade certifi
    
  • 设置环境变量REQUESTS_CA_BUNDLE,指向certifi的证书文件路径(替换XX为你的Python版本号):
    setx REQUESTS_CA_BUNDLE "C:\PythonXX\Lib\site-packages\certifi\cacert.pem"
    
    设置完成后重启VS Code,让环境变量生效。

2. GitHub Actions(OIDC)环境

在Workflow中安装依赖时升级certifi,并配置环境变量指定证书路径:

steps:
  - uses: actions/checkout@v4
  - name: Set up Python
    uses: actions/setup-python@v5
    with:
      python-version: '3.10'
  - name: Install dependencies
    run: |
      python -m pip install --upgrade pip
      pip install azure-monitor-query azure-identity certifi
  - name: Run script
    env:
      REQUESTS_CA_BUNDLE: ${{ env.pythonLocation }}/lib/python3.10/site-packages/certifi/cacert.pem
    run: python your_script.py |& tee -a output.txt

3. 显式配置Azure SDK的证书验证

在创建MetricsQueryClient时,通过Transport配置强制启用证书验证:

from azure.core.transport.requests import RequestsTransport
from azure.monitor.query import MetricsQueryClient
from azure.identity import DefaultAzureCredential
from datetime import timedelta
from azure.monitor.query import MetricAggregationType

cred = DefaultAzureCredential()
# 显式启用证书验证
transport = RequestsTransport(verify=True)
client_metrics = MetricsQueryClient(cred, transport=transport)

# 返回过去30天的每日交易数时间序列数据
response = client_metrics.query_resource(
    resource_id,
    metric_names=["Transactions"],
    timespan=timedelta(days=30),
    granularity=timedelta(days=1),
    aggregations=[MetricAggregationType.TOTAL]
)

原理说明

启用证书验证后,Python会使用可信的根CA证书库验证management.azure.com服务器的SSL证书,确认服务器身份的合法性,避免中间人攻击风险,彻底消除安全警告并提升连接安全性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.27 10:15:27