1

我的任务是将 repos 迁移到 gitlab,我决定使用 python-gitlab 自动化这个过程。除了二进制文件或二进制文件,如编译的目标文件 ( .o ) 或 .zip 文件,一切正常。(我知道存储库不是存放二进制文件的地方。我使用我得到的和被告知要做的事情。)

我可以使用以下方式上传它们:

import gitlab

project = gitlab.Gitlab("git_adress", "TOKEN")

bin_content = base64.b64encode(open("my_file.o", 'rb').read() ).decode()

接着:

data = {'branch':'main', 'commit_message':'go away', 'actions':[{'action': 'create', 'file_path': "my_file.o", 'content': bin_content, 'encode' : 'base64'}]}

project.commits.create(data)

问题是 gitlab 存储库中此类文件的内容类似于:

f0VMRgIBAQAAAAAAAAAAAAAEAPgABAAAAAAAAAAAAA....

这不是我想要的。如果我不这样做,.decode()我会收到错误消息:

TypeError:字节类型的对象不是 JSON 可序列化的

这是预期的,因为我发送了以二进制模式打开并使用base64.

我希望像使用 Web GUI“上传文件”选项上传这些文件一样上传/存储这些文件。

是否可以使用 python-gitlab API 来实现这一点?如果是这样,怎么做?

4

1 回答 1

2

问题是 Python 的base64.b64encode函数将为您提供一个字节对象,但 REST API(特别是 JSON 序列化)需要字符串。你想要的论点encoding也不是encode

这是要使用的完整示例:

from base64 import b64encode
import gitlab
GITLAB_HOST = 'https://gitlab.com'
TOKEN = 'YOUR API KEY'
PROJECT_ID = 123 # your project ID
gl = gitlab.Gitlab(GITLAB_HOST, private_token=TOKEN)
project = gl.projects.get(PROJECT_ID)

with open('myfile.o', 'rb') as f:
    bin_content = f.read()
b64_content = b64encode(bin_content).decode('utf-8')
# b64_content must be a string!

f = project.files.create({'file_path': 'my_file.o',
                          'branch': 'main',
                          'content': b64_content,
                          'author_email': 'test@example.com',
                          'author_name': 'yourname',
                          'encoding': 'base64',  # important!
                          'commit_message': 'Create testfile'})

然后在 UI 中,您将看到 GitLab 已将内容正确识别为二进制,而不是文本:

二进制浏览器 gitlab

于 2021-11-03T18:46:00.460 回答