How can I add files to GitLab with `python-gitlab`? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Web Scraping & Web Development (https://python-forum.io/forum-13.html) +--- Thread: How can I add files to GitLab with `python-gitlab`? (/thread-11300.html) |
How can I add files to GitLab with `python-gitlab`? - bingobingolotto - Jul-02-2018 Using Django, I’d like to sync the files in the database with git repositories on my GitLab instance via python-gitlab .My code: import gitlab import base64 import os from .models import Meme from django.conf import settings class Sync: def sync () : gl = gitlab.Gitlab('<GitLab URL>', private_token='xxxxxxxxxxxxxx') for meme in Meme.objects.all(): meme_title = meme.meme_title meme_file = str(meme.meme_file) root = settings.MEDIA_ROOT place = os.path.join(root, meme_file) # Create a new project on GitLab. project = gl.projects.create({'name': meme_title }) data = { 'branch': 'master', 'commit_message': 'Automatic commit via sync.py.', 'actions': [ { # Binary files need to be base64 encoded 'action': 'create', 'file_path': place, 'content': base64.b64encode(open(place, "rb").read()), 'encoding': 'base64', } ] } commit = project.commits.create(data)I’m getting the following traceback: What am I doing wrong? Why is type bytes not fitting?
RE: How can I add files to GitLab with `python-gitlab`? - buran - Jul-02-2018 based on this example on line#29 you should use 'r' mode, not 'rb' https://python-gitlab.readthedocs.io/en/stable/gl_objects/commits.html RE: How can I add files to GitLab with `python-gitlab`? - snippsat - Jul-02-2018 JSON format only supports Unicode strings. you can decode to string(which is Unicode by default in Python 3),be using decode() or decode('ascii') as Base64 encodes bytes to ASCII-only bytes.Error: >>> import base64 >>> import json >>> >>> place = base64.b64encode(open('foo.txt', "rb").read()) >>> place b'aGVsbG8gd29ybGQNCg0K' >>> type(place) <class 'bytes'> >>> d = {} >>> d['name'] = place >>> json.dumps(d) Traceback (most recent call last): File "<string>", line 428, in runcode File "<interactive input>", line 1, in <module> File "C:\Python37\lib\json\__init__.py", line 231, in dumps return _default_encoder.encode(obj) File "C:\Python37\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Python37\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Python37\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type bytes is not JSON serializableFix: >>> import base64 >>> import json >>> >>> place = base64.b64encode(open('foo.txt', "rb").read()).decode() # Or decode('ascii') >>> type(place) <class 'str'> >>> d = {} >>> d['name'] = place >>> json.dumps(d) '{"name": "aGVsbG8gd29ybGQNCg0K"}' |