如果我運行這樣的發布請求,它會起作用:
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 中,引數仍然是淺色的,這表明引數實際上并沒有在函式中使用。
也許我在編碼字串時做錯了,但無法弄清楚到底是什么。
uj5u.com熱心網友回復:
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)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/489582.html
標籤:Python python-3.x 卷曲 urllib urllib3
