我使用的是python3.8
这里需要用到一个库,是python-gitlab
先去gitlab生成一个token
这里有一个小坑,我花了1天才排除,就是建立token的时候,默认需要把API的权限给选择上,要不然,你用这个token,根本没有办法做任何的事情。怎么生成token,上网搜搜吧。
新生成一个新的gitlab操作的class
我总共就用了2个函数
import gitlab
import base64
# pip install python-gitlab
class Gitlabapi:
def __init__(self, url, token):
self.url = url
self.token = token
self.conn = gitlab.Gitlab(url=self.url, private_token=self.token)
def get_file_blob(self, in_id, sha):
project = self.conn.projects.get(in_id)
return_file = project.repository_blob(sha)
content = base64.b64decode(return_file['content'])
return content
def get_project_tree(self, in_id, path=''):
project = self.conn.projects.get(in_id)
if path:
items = project.repository_tree(path=path, ref='master', get_all=True)
else:
items = project.repository_tree(ref='master', recursive=True, get_all=True)
return items
直接调用
#当然了,这里要import那个class
git_host = "http://abc.com" #这个就是标准的网址就可以
token = 'XXXXXXXXX'
new_git = Gitlabapi.Gitlabapi(git_host, token)
project_items = new_git.get_project_tree(in_id=20821)
因为我是想遍历某个项目的文件和文件夹,所以,我又在gitlab的库里面增加了一个函数
def get_project_tree(self, in_id, path=''):
接下来遍历那个文件夹,然后去取里面的所有的文件和内容
real_sha = temp_file['id']
file_content = new_git.get_file_blob(in_id=20821, sha=real_sha)
我自己而言,这个文件是yaml格式的,我就转成了yaml继续处理
yaml_type_file = yaml.load(file_content, Loader=yaml.FullLoader)