'Python-gitlab commit pdf

I am trying to commit a PDF using python-gitlab library. I am using the document found in https://python-gitlab.readthedocs.io/en/stable/gl_objects/commits.html.

I encode the pdf using

    {
        # Binary files need to be base64 encoded
        'action': 'create',
        'file_path': 'file.pdf',
        'content': base64.b64encode(open('file.pdf').read()),
        'encoding': 'base64',
    }

But I get an error:

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x9c in position 171: invalid start byte.

I then try to do

    {
        # Binary files need to be base64 encoded
        'action': 'create',
        'file_path': 'file.pdf',
        'content': base64.b64encode(open('file.pdf', 'rb').read()),
        'encoding': 'base64',
    }

Basically changing it to bytes, but then I will get an error

TypeError: Object of type bytes is not JSON serializable

When trying to commit the data using the command

commit = project.commits.create(data)

Which makes sense, since the data is now in bytes and cannot be serialized by json. How can I work around/or how should this be implemented?



Solution 1:[1]

You need to open your file in read-binary mode (rb) you also need to convert the result of base64.b64encode from bytes to a string.

'content': str(base64.b64encode(open('file.pdf', 'rb').read()), 'utf-8'),

A full example using the project files API:

gl = gitlab.Gitlab(...)
project = gl.projects.get(1234)
with open('file.pdf', 'rb') as mypdf:
    content = mypdf.read()

file_content = str(base64.b64encode(content), 'utf-8')

f = project.files.create({'file_path': 'file.pdf',
                          'branch': 'main',
                          'encoding': 'base64',
                          'content': file_content,
                          'author_email': '[email protected]',
                          'author_name': 'yourname',
                          'commit_message': 'Create pdf file'})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1