Python脚本生成Bitbucket PR时变量失效且报400错误,求助
解决Bitbucket PR创建脚本的400错误及JSON变量替换问题
当前代码的核心问题
你遇到的400错误是因为请求的Content-Type不正确,导致Bitbucket API无法解析你发送的JSON数据,误以为必填字段缺失。具体原因:
当使用data=json.dumps(data)时,requests默认会把请求头的Content-Type设为application/x-www-form-urlencoded,而Bitbucket的PR接口要求请求体是application/json格式。
修复当前代码的两种方法
方法1:使用requests内置的json参数(推荐)
直接传递Python字典给json参数,requests会自动帮你序列化JSON,并设置正确的Content-Type头:
import requests import json import os def raise_pull_request(src): print('Source branch: ' + src) repo = 'https://api.bitbucket.org/2.0/repositories/company/myrepo/pullrequests' my_uuid = '10b8-4dfa-a69a-67d1' data = { "title": "Demo PR", "source": { "branch": { "name": src } }, "destination": { "branch": { "name": "demo-destination" } }, "reviewers": [ { "uuid": my_uuid } ] } response = requests.post( repo, headers={'Authorization': 'Bearer {}'.format(os.environ["my_token"])}, json=data ) print(response.status_code) print(response.json())
方法2:手动设置Content-Type头
如果坚持用data=json.dumps(data),需要显式添加Content-Type: application/json头:
response = requests.post( repo, headers={ 'Authorization': 'Bearer {}'.format(os.environ["my_token"]), 'Content-Type': 'application/json' }, data=json.dumps(data) )
解决三重引号JSON变量不生效问题
如果因为PR数据量大,想使用多行JSON字符串(三重引号),可以用f-string格式化注入变量,注意保持JSON语法正确性:
import requests import os def raise_pull_request(src): print('Source branch: ' + src) repo = 'https://api.bitbucket.org/2.0/repositories/company/myrepo/pullrequests' my_uuid = '10b8-4dfa-a69a-67d1' json_str = f""" {{ "title": "Demo PR", "source": {{ "branch": {{ "name": "{src}" }} }}, "destination": {{ "branch": {{ "name": "demo-destination" }} }}, "reviewers": [ {{ "uuid": "{my_uuid}" }} ] }} """ response = requests.post( repo, headers={ 'Authorization': 'Bearer {}'.format(os.environ["my_token"]), 'Content-Type': 'application/json' }, data=json_str.strip() ) print(response.status_code) print(response.json())
注:用f-string时,JSON里的{}需要写成{{}}转义,避免被当成格式化占位符。
也可以用str.format()方法,适合变量较多的场景:
json_str = """ { "title": "Demo PR", "source": { "branch": { "name": "{src_branch}" } }, "destination": { "branch": { "name": "demo-destination" } }, "reviewers": [ { "uuid": "{reviewer_uuid}" } ] } """.format(src_branch=src, reviewer_uuid=my_uuid)
额外注意事项
- 必须导入
os模块,否则os.environ["my_token"]会报错; - 确保
os.environ["my_token"]能正确获取有效的Bitbucket授权令牌; - 可打印
response.text或response.json()查看详细错误信息,辅助排查问题。
内容的提问来源于stack exchange,提问作者Technext
相关产品推荐
相关产品推荐

