You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python函数构造JSON请求体传参失效 调用Bitbucket API报错

问题原因

${变量名}是JavaScript模板字符串的插值语法,Python不支持该写法。你用三引号定义的data是普通字符串,其中的${bitbucket_branch}、${pipeline_name}不会替换为传入的函数参数,会作为纯文本直接提交给接口,这就是接口返回找不到分支${bitbucket_branch}、VSCode提示两个参数未被使用的根本原因——这两个参数确实没有在函数体内被实际引用。
另外手动拼接JSON字符串很容易出现多逗号、引号不匹配的格式错误,不建议用这种方式构造请求体。

修复方法

直接用Python标准库json将Python字典序列化为标准JSON格式字符串作为请求体,从根源避免变量替换失效、JSON格式错误的问题,修复后完整代码如下:

import urllib3
import json

def myFunction(bitbucket_branch, pipeline_name):
    contentTypeHeader = {
        'Content-type': 'application/json',
    }
 
    # 用字典构造请求体结构,直接引用传入参数
    data = json.dumps({
        "target": {
            "ref_type": "branch",
            "type": "pipeline_ref_target",
            "ref_name": bitbucket_branch,
            "selector": {
                "type": "custom",
                "pattern": pipeline_name
            }
        },
        "variables": []
    })

    http = urllib3.PoolManager()
    headers = urllib3.make_headers(basic_auth='{}:{}'.format("username", "password"))
    headers.update(contentTypeHeader)
    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("master", "mypipeline")
可选的字符串插值写法(不推荐)

如果你坚持要直接写JSON字符串,Python3.6及以上版本支持f-string插值,需要在字符串前加f标识,同时JSON本身的大括号需要写双份转义,示例如下:

data = f"""
{{
"target": {{
  "ref_type": "branch",
  "type": "pipeline_ref_target",
  "ref_name": "{bitbucket_branch}",
  "selector": {{
    "type": "custom",
    "pattern" : "{pipeline_name}"
  }}
}},
"variables": []
}}
"""

这种写法转义规则繁琐,很容易写出格式错误的JSON,没有特殊需求不要用。


内容的提问来源于stack exchange,提问作者Jnl

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 08:18:28