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-Type
在headers
成Accept
,得到了另一个响应代码415 (Unsupported Media Type)
:
headers = {'Accept': 'application/json'}
>> r = <Response [415]>
触发构建的文档显示你需要发送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
字典中。
Martijn,非常感谢!在看到您的解决方案之前,我将数据指定为:
data = "<build><buildType id=\"MyTestBuild\"/></build>"
。为了如果数据变得更加复杂,我的简单方法就是容易出错。