pythongitlabpython-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. Now I would like to add/upload this file to my Gitlab project repository directly by using python-gitlab library. 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?


Solution

  • You can use the files API to create a file. If you're using the python-gitlab wrapper, you use it like so as described in the documentation:

    import base64
    # ... generated your excel file 
    
    project = gl.projects.get(123) # use your project ID
    
    with open('myfile.xlsx', 'rb') 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')