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

使用Python脚本创建Grafana用户后无法在管理界面显示求助

问题排查与解决

核心问题1:Grafana API端点错误

你的GRAFANA_URL设置成了https://kirannbobby.grafana.net/login,这会导致后续拼接API路径时生成无效地址:https://kirannbobby.grafana.net/login/api/admin/users,完全偏离了Grafana创建用户的正确API端点。

正确的URL应该是Grafana实例的根地址:

GRAFANA_URL = 'https://kirannbobby.grafana.net'

核心问题2:错误的状态码判断逻辑

Grafana的/api/admin/users接口创建用户成功时,返回的状态码是201 Created,而非200。你当前的判断逻辑把非API场景的200响应(比如/login页面加载成功)误判为用户创建成功,导致错误的“创建成功”提示。

修改后的判断逻辑:

if response.status_code == 201:
    print(f'Successfully created user: {user["name"]}')
else:
    print(f'Failed to create user: {user["name"]}, Status Code: {response.status_code}, Response: {response.text}')

核心问题3:登录验证的端点错误

你直接POST到/login页面(Web登录入口),而非Grafana的登录API接口。正确的登录API是/api/login,且需要通过响应中的authToken字段判断是否登录成功,单纯判断状态码200并不准确。

修正后的登录验证代码:

# Validate the user's credentials by logging in
login_data = {
    'user': user['login'],
    'password': user['password']
}
response = requests.post(
    f'{GRAFANA_URL}/api/login',
    json=login_data
)

# Check if the login was successful
if response.status_code == 200 and 'authToken' in response.json():
    print(f'Successfully logged in as user: {user["name"]}')
else:
    print(f'Failed to log in as user: {user["name"]}, Status Code: {response.status_code}, Response: {response.text}')

额外验证步骤

  1. 执行脚本前,先用curl测试API权限,确认你的账号具备管理员权限(Grafana Cloud主账号默认拥有该权限):
curl -u "kirannbobby:your_password" -X POST -H "Content-Type: application/json" -d '{"name":"Test User","email":"test@example.com","login":"testuser","password":"testpass"}' https://kirannbobby.grafana.net/api/admin/users
  1. 在脚本中添加print(response.text),查看API返回的具体错误信息,辅助排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 09:02:20