[英]Upload binary files using python-gitlab API
我的任務是將 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 存儲庫中此類文件的內容類似於:
f0VMRgIBAQAAAAAAAAAAAAEAPgABAAAAAAAAAAAAA....
這不是我想要的。 如果我不.decode()
我得到錯誤說:
類型錯誤:字節類型的對象不是 JSON 可序列化的
這是預期的,因為我發送了以二進制模式打開並使用base64
編碼的文件。
我想上傳/存儲這些文件,就像我使用 Web GUI“上傳文件”選項上傳它們一樣。
是否可以使用 python-gitlab API 實現這一點? 如果是這樣,如何?
問題在於 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 已將內容正確識別為二進制,而不是文本:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.