Warm tip: This article is reproduced from serverfault.com, please click

post-如何使用Python请求模块和TeamCity API触发构建?

(post - How to use Python requests module and TeamCity API to trigger a build?)

发布于 2016-04-26 20:43:20

TeamCity 9.x文档部分Triggering a Build有一个cURL示例

curl -v -u user:password http://teamcity.server.url:8111/app/rest/buildQueue --request POST --header "Content-Type:application/xml" --data-binary @build.xml

我想知道如何将其转换为等效的Python脚本(使用POST来自requests模块的请求)?


顺便说一句,我尝试了以下Python脚本,但得到了这样的响应代码400 (Bad Request)

url = "http://myteamcity.com:8111/httpAuth/app/rest/buildQueue/"
headers = {'Content-Type': 'application/json'}
data = json.dumps({'buildTypeId': 'MyTestBuild'})
r = requests.post(url, headers=headers, data=data, auth=("username", "password"), timeout=10)
print "r = ", r

>> r =  <Response [400]>

如果变化Content-TypeheadersAccept,得到了另一个响应代码415 (Unsupported Media Type)

headers = {'Accept': 'application/json'}

>> r =  <Response [415]>
Questioner
Zhongde Yu
Viewed
0
2016-04-27 23:41:30

触发构建的文档显示你需要发送XML而不是JSON:

<build>
    <buildType id="buildConfID"/>
</build>

TeamCity REST API有点复杂。有些方法同时接受XML和JSON,有些仅接受XML。这是后一种方法之一。他们将根据你设置Accept标头的内容以XML或JSON进行响应

发送以上内容和你所需的内部版本ID;对于一个简单的XML文档,你可以使用模板:

from xml.sax.saxutils import quoteattr

template = '<build><buildType id={id}/></build>'

url = "http://myteamcity.com:8111/httpAuth/app/rest/buildQueue/"
headers = {'Content-Type': 'application/xml'}
build_id = 'MyTestBuild'
data = template.format(id=quoteattr(build_id))

r = requests.post(url, headers=headers, data=data, auth=("username", "password"), timeout=10)

请注意,我使用该xml.sax.saxutils.quotattr()函数来确保build_id正确引用的值以包含为XML属性。

这将产生XML;如果要处理JSON响应,请添加'Accept': 'application/json'headers字典中。