从另一个 gitlab 存储库访问私有文件

Accessing a private file from another gitlab repository

提问人:Miguel Crespo 提问时间:11/16/2023 更新时间:11/16/2023 访问量:19

问:

我正在构建一个 CI 管道,我想从不同的私有存储库读取特定文件。我是这两个存储库的所有者,但计划是向我的同事开放一个,同时将第二个存储库作为基线和私有,只有我才能访问。这里存储了来自不同测试的预期结果,管道应在运行时将获得的结果与基线进行比较。

但是,我不断运行请求错误,其中文件无法访问(响应状态代码 403)

我尝试使用 python 通过请求检索文件:

# GitLab private token
PRIVATE_TOKEN = 'my-private-token'
# The URL of the raw file in the private repository
FILE_URL = 'https://gitlab.com/{username}/{repo-name}/-/raw/main/{file1}'

# Set up the headers for authentication
headers = {'Authorization': f'token {PRIVATE_TOKEN}'}

以及

headers = {'Authorization': f'Bearer {PRIVATE_TOKEN}'}

最终调用请求

response = requests.get(FILE_URL, headers=headers)

但始终收到响应状态代码 403

python gitlab 请求 gitlab-ci

评论


答:

0赞 sytech 11/16/2023 #1

私有令牌仅允许您访问 API URL,而不允许访问前端 UI URL。

例如,若要获取文件内容,需要使用存储库文件 API

from base64 import b64decode

headers = {'PRIVATE-TOKEN': PRIVATE_TOKEN}
branch = 'main'
project_id = 278964
params = {'ref': branch}
api_url = f'https://gitlab.com/api/v4/projects/{project_id}/repository/files/{file_name}'
resp = requests.get(api_url, headers=headers, params=params)
resp.raise_for_status()
encoded_contents = resp.json()['content']
decoded_contents_bytes = b64decode(encoded_contents)

print(decoded_contents_bytes)

由于您使用的是 Python,因此与 API 交互的一种便捷方法是使用 python-gitlab

import gitlab  # pip install python-gitlab
TOKEN = 'your private token'
gl = gitlab.Gitlab('https://gitlab.com', private_token=TOKEN)

project_id = 'gitlab-org/gitlab'  # or use numerical ID

project = gl.projects.get(project_id)
raw_content = project.files.raw(
    file_path='.gitlab-ci.yml', 
    ref=project.default_branch
)

print(raw_content)