使用
python-gitlab
模块来调用gitlab的API来管理gitlab
install
pip install python-gitlab# 如果是安装到Python3使用可以使用如下命令pip3 install python-gitlab
配置
为了保护API 用到的 private_token,一般会将其写到系统的配置文件中去/etc/python-gitlab.cfg
或者 ~/.python-gitlab.cfg
配置示例:
root@pts/1 $ cat ~/.python-gitlab.cfg [global] default = kaishugit ssh_verify = Falsetimeout = 8[kaishugit] url = http://10.0.0.6private_token = xxxxx-V4Yxxxxxxks7u api_version = 3
程序使用
在程序中使用的时候可以直接用如下方式调用
## logingl = gitlab.Gitlab.from_config('kaishugit', ['~/.python-gitlab.cfg'])
examples
## 得到第一页project列表projects = gl.projects.list()## 得到所有projectprojects = gl.projects.list(all=True) projects = gl.projects.all()
参考
附加
自定义脚本获取指定用户或者分组或者全部的代码仓库地址
#!/usr/bin/env python3# encoding: utf-8#__Author__ = 'Colin'__Date__ = '2018-06-20'import gitlabimport osimport sysclass GitlabAPI(object): def __init__(self, *args, **kwargs): if os.path.exists('/etc/python-gitlab.cfg'): self.gl = gitlab.Gitlab.from_config('kaishugit', ['/etc/python-gitlab.cfg']) elif os.path.exists(os.getenv('HOME') + '/.python-gitlab.cfg'): self.gl = gitlab.Gitlab.from_config('kaishugit', [os.getenv('HOME') + '/.python-gitlab.cfg']) else: print('You need to make sure there is a file named "/etc/python-gitlab.cfg" or "~/.python-gitlab.cfg"') sys.exit(5) def get_user_id(self, username): user = self.gl.users.get_by_username(username) return user.id def get_group_id(self, groupname): group = self.gl.users.search(groupname) return group[0].id def get_all_projects(self): projects = self.gl.projects.list(all=True) result_list = [] for project in projects: result_list.append(project.http_url_to_repo) return result_list def get_user_projects(self, userid): projects = self.gl.projects.owned(userid=userid, all=True) result_list = [] for project in projects: result_list.append(project.http_url_to_repo) return result_list def get_group_projects(self, groupname): projects = self.gl.projects.owned(groupname=groupname, all=True) result_list = [] for project in projects: result_list.append(project.http_url_to_repo) return result_listif __name__ == '__main__': username='caichenyu' git = GitlabAPI() userid = git.get_user_id(username) print(username + '->' + str(userid)) userprojects = git.get_user_projects(userid) print(userprojects)
作者:全栈运维
链接:https://www.jianshu.com/p/615335e40be7
点击查看更多内容
为 TA 点赞
评论
共同学习,写下你的评论
评论加载中...
作者其他优质文章
正在加载中
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦