使用python-gitlab推送JPG至GitLab仓库遇UnicodeDecodeError求助
解决python-gitlab推送JPG图片时的UnicodeDecodeError问题
问题根源在于GitLab API要求二进制文件内容需以Base64编码字符串传递,你直接传入原始二进制字节后,python-gitlab库会尝试用UTF-8解码这些字节,从而触发编码错误。
修改方案如下:
- 导入
base64模块,将读取的二进制图片内容编码为Base64字符串 - 将编码后的字符串传入
files.create的content参数
修改后的代码:
import gitlab import base64 gl = gitlab.Gitlab(GITLAB_URL, PRIVATE_TOKEN) project = gl.projects.get(PROJECT_ID) with open(file_path, 'rb') as f: file_content = f.read() # 将二进制内容编码为Base64字符串 encoded_content = base64.b64encode(file_content).decode('utf-8') branch = project.branches.get('main') project.files.create( { 'file_path': f"{REPOSITORY_PATH}/{PATH_IN_REPO}", 'branch': branch.name, 'content': encoded_content, 'commit_message': commit_message } )
补充说明:
- JPG属于二进制文件,无法用UTF-8编码解析,必须通过Base64转成可被API识别的文本格式
base64.b64encode()返回字节对象,需要用decode('utf-8')转成字符串才能符合API参数要求
内容的提问来源于stack exchange,提问作者Limone
相关产品推荐
相关产品推荐

