Python 使用Gitlab Api

发布于:2025-06-25 ⋅ 阅读:(22) ⋅ 点赞:(0)

代码

REST API

见自带帮助文档

python

安装python-gitlab

pip install --upgrade python-gitlab

使用API

参考:https://python-gitlab.readthedocs.io/en/stable/api-usage.html

import gitlab

# anonymous read-only access for public resources (GitLab.com)
gl = gitlab.Gitlab()

# anonymous read-only access for public resources (self-hosted GitLab instance)
gl = gitlab.Gitlab('https://gitlab.example.com')

# private token or personal token authentication (GitLab.com)
gl = gitlab.Gitlab(private_token='JVNSESs8EwWRx5yDxM5q')

# private token or personal token authentication (self-hosted GitLab instance)
gl = gitlab.Gitlab(url='https://gitlab.example.com', private_token='JVNSESs8EwWRx5yDxM5q')

# oauth token authentication
gl = gitlab.Gitlab('https://gitlab.example.com', oauth_token='my_long_token_here')

删除流水线

from bs4 import BeautifulSoup
import requests
import re 
import time
import json
import os
import gitlab

from datetime import datetime, timedelta
from dateutil import parser




deadline = datetime.today() - timedelta(days=3)






headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/106.0.0.0 Safari/537.36', 'Accept-Language':'zh-CN,zh;q=0.9'}

#全局变量
baseUrl="http://192.168.x.x"
privateToken="xxxxxxx"

 
   
    

def listProject(gl):
    projects = gl.projects.list(iterator=True)
    for project in projects:
        print(f"name:{project.path_with_namespace},id:{project.id} \n")




def deleteProjectById(gl,pjId):
    project = gl.projects.get(pjId)
    deleteProject(project)

def deleteProject(project):
    deleteProjectPipelines(project)


def deleteProjectPipelines(project):
    pipelines = project.pipelines.list(iterator=True)
    for pipeline in pipelines:
        deletePipeline(project,pipeline);



def deletePipeline(project,pipeline):
    createdAt = parser.isoparse(pipeline.created_at).replace(tzinfo=None)
 
    if createdAt < deadline :
        print("delete pipeline: " + str(project.id) + "," + str(pipeline.id) )
        pipeline.delete()
        time.sleep(2)




if __name__ == "__main__": # 运行入口
    gl = gitlab.Gitlab(baseUrl, private_token=privateToken)
    deleteProjectById(gl,421)
  




附录

参考

REST API 资源:https://gitlab.cn/docs/jh/api/api_resources.html

Python-Gitlab API:https://python-gitlab.readthedocs.io/en/stable/index.html

其他包

pip3 install beautifulsoup4

网站公告

今日签到

点亮在社区的每一天
去签到