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

如何在Prometheus Client的push_to_gateway函数中传递Basic Auth用户名和密码

通过Prometheus Client的push_to_gateway推送指标至带Basic Auth的服务器

要给开启Basic Auth认证的Prometheus Push Gateway推送指标,你可以通过push_to_gateway函数的handler参数传入自定义的认证处理器,具体实现方式如下:

1. 导入必要模块

需要用到Prometheus Client的核心类,以及Python标准库的HTTP认证处理器:

from prometheus_client import CollectorRegistry, Gauge, push_to_gateway
from urllib.request import HTTPBasicAuthHandler, build_opener

2. 配置认证信息并初始化指标

设置你的Basic Auth用户名、密码,同时创建指标注册表和要推送的指标:

# 替换为你的实际认证信息
username = "your_auth_username"
password = "your_auth_password"

# 创建指标注册表
registry = CollectorRegistry()
# 定义示例指标(根据你的实际需求调整)
example_gauge = Gauge('service_request_count', 'Total number of service requests', registry=registry)
example_gauge.set(156)

3. 创建带Basic Auth的请求处理器

构建支持认证的HTTP请求 opener:

# 创建Basic Auth处理器,uri参数可指定网关地址(留空则自动匹配目标URL)
auth_handler = HTTPBasicAuthHandler()
auth_handler.add_password(
    realm=None,
    uri='http://your-push-gateway:9091/',
    user=username,
    passwd=password
)

# 构建带认证的opener
auth_opener = build_opener(auth_handler)

4. 调用push_to_gateway完成推送

将自定义的auth_opener.open作为handler传入函数:

push_to_gateway(
    gateway='your-push-gateway:9091',  # 替换为你的Push Gateway地址
    job='backend_service',             # 替换为你的任务标识
    registry=registry,
    handler=auth_opener.open           # 传入带认证的handler
)

注意事项

  • 不推荐直接将用户名密码拼接在URL中(如http://user:pass@gateway:9091),这种方式可能导致密码泄露在日志或进程参数中。
  • 如果你的Push Gateway使用HTTPS,只需将URL中的http替换为https即可,上述认证逻辑同样适用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 21:12:17