import time import requests import json base_url = "https://git.ixiaochuan.cn" token = "ZwVrC_RyUZHM9ozKZdQy" # token = "J4M87_ysRCJbry-5ec35" # 获取所有项目 def get_all_projects(): headers = { 'PRIVATE-TOKEN': token } plist = [] for i in range(200): i = i + 1 per_page = 20 url = f"{base_url}/api/v4/projects?per_page={per_page}&page={i}" print(url) response = requests.get(url, headers=headers) pjson = response.json() for j in pjson: pdict = {} pdict['path'] = j.get('path_with_namespace') pdict['id'] = j.get('id') pdict['name'] = j.get('name') plist.append(pdict) time.sleep(1) with open('projects.json', 'w') as f: f.write(json.dumps(plist)) return plist # 获取用户id def get_user_id(): url = base_url + '/api/v4/user' headers = { 'PRIVATE-TOKEN': token } response = requests.get(url, headers=headers) print(response.json()) user_id = response.json().get('id') return user_id # 给用户授权项目 def grant_repo2user(pid, uid, role): url = base_url + f'/api/v4/projects/{pid}/members' headers = {'PRIVATE-TOKEN': token} data = {'user_id': uid, 'access_level': role} resonse = requests.post(url, headers=headers, data=data) if resonse.status_code == 201: print('授权成功') else: print('授权失败,错误信息:', resonse.text) if __name__ == '__main__': # 40 代表master 30 dev 20 reporter 10 guest role = 40 uid = get_user_id() print(uid) # 测试授权 # grant_repo2user(pid, uid, role) # 获取项目列表,并存入文件 # get_all_projects() with open('projects.json', 'r') as f: project_list = json.loads(f.read()) for i in project_list: pid = i.get('id') grant_repo2user(pid, uid, role) time.sleep(1) print('所有授权完成')