使用Bitbucket仓库级HTTP令牌创建文件遇邮箱必填错误的解决咨询
解决Bitbucket仓库级HTTP令牌创建文件的400错误问题
仓库级HTTP访问令牌确实无法关联邮箱,但你可以通过在API请求中显式指定提交作者的邮箱和名称来解决这个报错。Bitbucket Server的文件创建API支持传入author参数,只要邮箱格式合法即可,无需对应真实存在的账号。
修改代码方案
推荐改用JSON格式发送请求(更符合API设计规范),调整后的代码如下:
import json import requests def handler(context, inputs): jsonOut = json.dumps(inputs, separators=(',', ':')) print("Inputs were {0}".format(jsonOut)) # Set the API endpoint URL project = '{project name}' repo = '{repo name}' fileName = 'test789.txt' url = f'https://{{My Bitbucket server url}}/rest/api/latest/projects/{project}/repos/{repo}/browse/{fileName}' print('url: ' + url) token = "{my HTTP access token}" # Set the headers with the encoded key (添加Content-Type) headers = { 'Authorization': f'Bearer {token}', 'Accept': 'application/json', 'Content-Type': 'application/json' } # Set the body for the API call (添加author字段) branchName = 'branch-name' content = inputs['contents'] commitMsg = 'Test creating a file with a python script' data = { 'branch': branchName, 'content': content, 'message': commitMsg, 'sourceBranch': 'master', 'author': { 'name': 'Repo Token Committer', # 自定义提交者名称 'email': 'committer@example.com' # 任意合法格式的邮箱 } } # Make the API call to create the new branch (改用json参数发送数据) response = requests.put(url, headers=headers, json=data, verify=False) # Check if the request was successful if response.status_code != 200: raise Exception("Status code: " + str(response.status_code) + "\n" + response.json()["errors"][0]["message"]) print("YML file pushed to BitBucket successfully.") inputs = {"contents": "Flippity Floo"} handler("context", inputs)
关键修改点
- 在请求头中添加
Content-Type: application/json,告知服务器请求体格式 - 在请求体中新增
author对象,包含name(自定义名称)和email(任意合法邮箱即可) - 将原
files参数替换为json参数,让requests自动序列化JSON数据
如果坚持使用表单格式提交,也可以将author序列化为JSON字符串后放入files字典中:
files = { 'branch': branchName, 'content': content, 'message': commitMsg, 'sourceBranch': 'master', 'author': json.dumps({ 'name': 'Repo Token Committer', 'email': 'committer@example.com' }) }
内容的提问来源于stack exchange,提问作者B. Allred
相关产品推荐
相关产品推荐

