简体   繁体   English

通过 Python 在 Gitlab 项目存储库中添加文件

[英]Add a file in Gitlab project repository by Python

I have a python script where I have created an output file as an excel table.我有一个 python 脚本,我在其中创建了一个 output 文件作为 excel 表。 Now I would like to add/upload this file to my Gitlab project repository directly by using python-gitlab library.现在我想通过使用 python-gitlab 库直接将此文件添加/上传到我的 Gitlab 项目存储库。 I have found some solution where file was added local repository and then pushed to remote repository.我找到了一些解决方案,将文件添加到本地存储库,然后推送到远程存储库。 How can I push/upload directly to remote repository?如何直接推送/上传到远程存储库?

You can use the files API to create a file.您可以使用文件 API创建文件。 If you're using the python-gitlab wrapper, you use it like so as described in the documentation :如果你使用的是 python-gitlab 包装器,你可以像文档中描述的那样使用它:

import base64
# ... generated your excel file 

project = gl.projects.get(123) # use your project ID

with open('myfile.xlsx', 'wb') as my_file:
    contents = base64.b64encode(my_file.read()).decode('utf-8')


# create new file in the repo
f = project.files.create({'file_path': 'testfile.xlsx',
                          'branch': 'main',
                          'content': contents,
                          'encoding': 'base64',
                          'author_email': 'test@example.com',
                          'author_name': 'yourname',
                          'commit_message': 'Create testfile'})

Or to modify an existing file:或修改现有文件:

project = gl.projects.get(123)

# get the file object
f = projects.files.get(file_path='testfile.xlsx', ref='main')
# modify its contents
f.content = base64.b64encode(b'new content').decode('utf-8')

# save (commit) the new contents
f.save(branch='main', commit_message='update file', encoding='base64')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM