Python使用GitLab API来获取文件内容
import requests
def get_file_from_gitlab(project_id, file_path, ref, access_token):
"""
从GitLab拉取特定tag或分支的文件
:param project_id: GitLab项目的ID或路径
:param file_path: 文件在项目中的路径
:param ref: 分支或tag的名称
:param access_token: GitLab的访问令牌
:return: 文件内容
"""
url = f"https://gitlab.com/api/v4/projects/{project_id}/repository/files/{file_path}/raw"
headers = {
"PRIVATE-TOKEN": access_token
}
params = {
"ref": ref
}
response = requests.get(url, headers=headers, params=params)
if response.status_code == 200:
return response.text
else:
response.raise_for_status()
# 示例参数
project_id = "your_project_id_or_path" # 替换为你的项目ID或路径
file_path = "path/to/your/file.txt" # 替换为你要拉取的文件路径
ref = "your_tag_or_branch_name" # 替换为你的tag或分支名称
access_token = "your_access_token" # 替换为你的GitLab访问令牌
# 拉取文件内容
try:
file_content = get_file_from_gitlab(project_id, file_path, ref, access_token)
print("文件内容:")
print(file_content)
except requests.exceptions.HTTPError as err:
print(f"HTTP error occurred: {err}")
except Exception as err:
print(f"An error occurred: {err}")