python脚本通过Gerrit REST API 获取所有用户

本文介绍了如何在没有直接查询Gerrit用户名的RESTAPI接口时,通过获取用户ID并进一步查询获取用户名的过程,特别提到了处理XSSI保护前缀的技巧。
摘要由CSDN通过智能技术生成

自动化需要获取到所有的gerrit 用户,也就是username,查询 Gerrit的REST API并没有这样的Endpoint.
最终实现方法:先获取所有用户id,再根据id查询username。
这里需要注意:返回的json格式是有 XSSI 保护前缀的,所以需要先移除。

import requests
from requests.auth import HTTPBasicAuth
import json
def get_user_info(gerrit_url, username, password, account_id):
    url = f"{gerrit_url}/a/accounts/{account_id}"
    headers = {"Content-Type": "application/json"}
    response = requests.get(url, auth=HTTPBasicAuth(username, password), headers=headers)
    if response.status_code == 200:
        try:
            json_text = response.text.lstrip(")]}'")
            user_info = json.loads(json_text)

            return user_info.get("username")
        except json.JSONDecodeError:
            print(f"Error decoding JSON for user ID {account_id}")
            print("Response JSON:", response.text)
    else:
        print(f"Failed to retrieve user info for ID {account_id}. Status code: {response.status_code}, Response: {response.text}")

def list_users(username, password, gerrit_url):
    url = f"{gerrit_url}/a/accounts/?q=is:active"
    headers = {"Content-Type": "application/json"}
    response = requests.get(url, auth=HTTPBasicAuth(username, password), headers=headers)
    users_list = []

    if response.status_code == 200:
        try:
            json_text = response.text.lstrip(")]}'")
            users_data = json.loads(json_text)
            for user in users_data:
                account_id = user.get('_account_id')
                account_username = get_user_info(gerrit_url, username, password, account_id)
                users_list.append(account_username)

        except json.JSONDecodeError:
            print("Empty response or invalid JSON.")
    else:
        print(f"Error: {response.status_code} - {response.text}")

    return users_list
  • 11
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值