使用 python 个请求发布 XML

Posting XML using python requests

我有以下代码 posts xml 到 teamcity 以创建新的 VCS 根目录:

def addVcsRoot(vcsRootId, vcsRootName, projectId, projectName, buildName, repoId, teamAdminUser, teamAdminPass):
     headers = {'Content-type': 'application/xml'}
     data = ("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>" +
        "<vcs-root id=\"" + vcsRootId + "\" " + "name=\"" + vcsRootName + "\" " +
        "vcsName=\"jetbrains.git\" href=\"/app/rest/vcs-roots/id:" + vcsRootId + "\">" +
        "<project id=\"" + projectId + "\" " "name=\"" + projectName + "\" " "parentProjectId=\"_Root\" " +
        "description=\"Single repository for all components\" href=\"/app/rest/projects/id:" + projectId +  
        "\" " + "webUrl=\"http://teamcity.company.com/project.html?projectId=" + projectId + "\"/>" +
        "<properties count=\"11\">" + "<property name=\"agentCleanFilesPolicy\" value=\"ALL_UNTRACKED\"/>" +
        "<property name=\"agentCleanPolicy\" value=\"ON_BRANCH_CHANGE\"/>" +
        "<property name=\"authMethod\" value=\"PASSWORD\"/>" +
        "<property name=\"branch\" value=\"refs/heads/master\"/>" +
        "<property name=\"ignoreKnownHosts\" value=\"true\"/>" +
        "<property name=\"submoduleCheckout\" value=\"CHECKOUT\"/>" +
        "<property name=\"url\" value=\"https://source.company.com/scm/" +repoId +  "/" + buildName + 
        ".git\"" + "/>" + "<property name=\"username\" value=\"" + teamAdminUser + "\"/>" +
        "<property name=\"usernameStyle\" value=\"USERID\"/>" +
        "<property name=\"secure:password\" value=\"" + teamAdminPass + "\"/>" +
        "<property name=\"useAlternates\" value=\"true\"/>" + "</properties>" +
        "<vcsRootInstances href=\"/app/rest/vcs-root-instances?locator=vcsRoot:(id:" + vcsRootId + ")" +
        "\"" + "/>" + "</vcs-root>")
     url = path + 'vcs-roots'
     return requests.post(url, auth=auth, headers=headers, data=data)

我确实看到了 xml 文件应该是什么样子,并且已经制作好了,这样我就可以为不同的构建输入不同的参数,并且脚本运行良好。我的问题是:有没有更优雅的方法来做到这一点?将这个长字符串串联起来似乎很丑陋且效率低下。 post xml 使用请求还有哪些其他方法?

我不打算全部重写,但使用 str.format、kwargsa 和三引号字符串会使代码变得不那么混乱:

def addVcsRoot(**kwargs):
    headers = {'Content-type': 'application/xml'}

    data = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
        <vcs-root id="{vcsRootId}"  name="{vcsRootName}"
        "vcsName="jetbrains.git" href="/app/rest/vcs-roots/id:"{vcsRootId}"\>""".format(**kwargs)

然后:

addVcsRoot(vcsRootId=1234, ......)

或者如果你想保持命名参数不变:

def addVcsRoot(vcsRootId, vcsRootName, projectId, projectName, buildName, repoId, teamAdminUser, teamAdminPass)
    headers = {'Content-type': 'application/xml'}

    data = """<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <vcs-root id="{vcsRootId}"  name="{vcsRootName}"
    "vcsName="jetbrains.git" href="/app/rest/vcs-roots/id:"{vcsRootId}"\>"""\
    .format(vcsRootI=vcsRootId, vcsRootName=vcsRootName.....)