如果我运行这样的发布请求,它会起作用:
def myFunction():
contentTypeHeader = {
'Content-type': 'application/json',
}
data = """
{
"target": {
"ref_type": "branch",
"type": "pipeline_ref_target",
"ref_name": "master",
"selector": {
"type": "custom",
"pattern" : "mypipeline"
}
},
"variables": []
}
"""
http = urllib3.PoolManager()
headers = urllib3.make_headers(basic_auth='{}:{}'.format("username", "password"))
headers = dict(list(contentTypeHeader .items()) + list(headers.items()))
try:
resp = http.urlopen('POST', 'https://api.bitbucket.org/2.0/repositories/owner/slugg/pipelines/', headers=headers, body=data)
print('Response', str(resp.data))
except Exception as e:
print('Error', e)
myFunction()
但是,如果不是对值进行硬编码,而是尝试将它们作为函数传递:
def myFunction(bitbucket_branch, pipeline_name):
contentTypeHeader = {
'Content-type': 'application/json',
}
data = """
{
"target": {
"ref_type": "branch",
"type": "pipeline_ref_target",
"ref_name": "${bitbucket_branch}",
"selector": {
"type": "custom",
"pattern" : "${pipeline_name}"
}
},
"variables": []
}
"""
...
myFunction("master","mypipeline")
我收到此错误:
Response b'{"error": {"message": "Not found", "detail": "Could not find last reference for branch ${bitbucket_branch}", "data": {"key": "result-service.pipeline.reference-not-found", "arguments": {"uuid": "${bitbucket_branch}"}}}}'
此外,在我的功能中:
def myFunction(bitbucket_branch, pipeline_name):
在我的 VSCode 中,参数仍然是浅色的,这表明参数实际上并没有在函数中使用。
也许我在编码字符串时做错了,但无法弄清楚到底是什么。
Python 不会${pipeline_name}
为您扩展字符串内部;这是 Javascript 模板字符串的一个特性(并且不是 JSON 的一部分)——所以除非你运行实际的 Javascript,否则这是行不通的。
但是,python 有 f-strings,它的作用相同:
def myFunction(bitbucket_branch, pipeline_name):
contentTypeHeader = {
'Content-type': 'application/json',
}
# notice the added f and removal of $
data = f"""
{
"target": {
"ref_type": "branch",
"type": "pipeline_ref_target",
"ref_name": "{bitbucket_branch}",
"selector": {
"type": "custom",
"pattern" : "{pipeline_name}"
}
},
"variables": []
}
"""
这将用{}
变量中的值替换字符串中的内容。我还想提一下,您可能希望将其声明为 Python 结构并用于json.dumps
将其转换为 JSON。这样,您就可以在 Python 中做任何您习惯的事情,而不是使用 JSON 模板并替换该模板中的值(如果这些值中的任何一个包含"
,在这种情况下,您最终会生成无效的 JSON)。
import json
def myFunction(bitbucket_branch, pipeline_name):
data = {
"target": {
"ref_type": "branch",
"type": "pipeline_ref_target",
"ref_name": bitbucket_branch,
"selector": {
"type": "custom",
"pattern" : pipeline_name
}
},
"variables": []
}
}
return json.dumps(data)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句