python 调用gitlab API

一、使用python对gitlab进行自动化操作

1.python-gitlab模块官网文档

2.gitlab官网文档

二、常用使用功能

//1.登录gitlab
def login():
    gl = gitlab.Gitlab('https://git.4399.com', private_token='dfmkbarHTTSLSGDsdqwt4')
    return gl
gl = login()

//2.获取指定项目(项目ID)
project = gl.projects.get(4920)

//3.查看此项目所有分支
branches = project.branches.list()
print branches

//4.查找分支,存在则删除
try:
    branch = project.branches.get('ReplaceWeb')
    project.branches.delete('ReplaceWeb')
    print u"删除旧分支成功"
except gitlab.exceptions.GitlabGetError as error:
    print(error)
    print u"旧分支不存在"

//5.创建分支
try:
    branch = project.branches.create({'branch': 'ReplaceWeb', 'ref': 'develop'})
    print u"创建新分支ReplaceWeb成功"
except gitlab.exceptions.GitlabCreateError as error:
    print(error)

//6.下载gitlab文件到本地,先打开本地文件,file_path是远程路径。
with open('D:/WebContent/AppConfig.h', 'wb') as f:
    project.files.raw(file_path='/src/main/AppConfig.h', ref='ReplaceWeb', streamed=True, action=f.write)
    print u"下载AppConfig.h成功"

//7.上传多文件,可以多次执行create、update、delete、move、chmod等操作
//需要注意的是,对于二进制文件,压缩包文件需要使用base64进行编码
data = {
    'branch': 'ReplaceWeb',
    'commit_message': 'update web file',
    'actions': [
        {
            'action': 'update',
            'file_path': '/assist/src/main/AppConfig.h',
            'content': open('D:/WebContent/AppConfig.h').read(),
        },
        {
            'action': 'update',
            'file_path': '/bin/web_content/assist_web.zip',
            'encoding': 'base64',
            'content': base64.b64encode(open('D:/WebContent/assist_web.zip', "rb").read()),
        }
    ]
}
project.commits.create(data)

//8.请求合并操作
mr = project.mergerequests.create({'source_branch': 'ReplaceWeb',
                                       'target_branch': 'develop',
                                       'title': 'update oa_web pack'})

你可能感兴趣的:(python)