如何从 python 重写 gitlab 中的 XML 文件

How to rewrite XML file in gitlab from python

我从 gitlab 读取 XML 文件到一个变量中,然后我用它做了一些操作。我需要使用该变量重写 gitlab 中的文件。当我使用 dump - 它会从文件中删除所有内容。如何从 python 重写 gitlab 中的 XML 文件?

import gitlab
import io
import xml.etree.ElementTree as ET

gl = gitlab.Gitlab(
                private_token='xxxxx')
gl.auth()

projects = gl.projects.list(owned=True, search='Python')
raw_content = projects[0].files.raw(file_path='9_XML/XML_hw.xml', ref='main')
f = io.BytesIO()
f.write(raw_content)
f.seek(0)
xml_file = ET.parse(f)  # read file 

..... some manipulations with xml_file


project_id = 111111
project = gl.projects.get(project_id)
f = project.files.get(file_path='9_XML/XML_hw.xml', ref='main')
f.content = ET.dump(xml_file) # IT doesn't rewrite, it deletes everything from the file
f.save(branch='main', commit_message='Update file')

ET.dump 不会产生 return 值。它只打印到标准输出。如the docs所述:

Writes an element tree or element structure to sys.stdout. This function should be used for debugging only.

因此,您最终设置 f.content = None

不使用 .dump,而是使用 .tostring:

xml_str = ET.tostring(xml_file, encoding='unicode')
f.content = xml_str