使用python请求发布XML

2024-09-27 17:46:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码将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文件应该是什么样子的,并制作了它,这样我就可以为不同的构建输入不同的参数,而且脚本运行得很好。我的问题是:有没有更优雅的方式来做这件事?用串联方式发布这个长字符串看起来既丑陋又低效。使用请求发布xml的其他方法有哪些?在


Tags: namerestidappurldatavalueproperty
1条回答
网友
1楼 · 发布于 2024-09-27 17:46:32

我不打算全部重写,而是用str.格式,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)

然后:

^{pr2}$

或者,如果要保持命名参数不变:

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.....)

相关问题 更多 >

    热门问题