如何在Python中使用Bearer令牌将HTML文件上传至Azure DevOps工作项?
如何在Python中使用Bearer令牌将HTML文件上传至Azure DevOps工作项?
首先直接解答你的三个核心疑问:
- 编码问题:不需要对HTML文件做Base64编码,直接读取文件内容并发送即可——HTML本质是纯文本格式,和普通文本文件的上传逻辑完全一致。
- 特殊Headers设置:除了必填的
Authorization: Bearer {你的令牌},需要将Content-Type设置为text/html来明确文件类型;另外还要加上Accept: application/json让API返回JSON格式的结果。 - HTML与文本文件的差异:没有本质差异!Azure DevOps的附件API对HTML文件的处理和普通文本文件完全相同,只是设置正确的
Content-Type能让平台识别文件类型,后续查看时会更友好。
接下来,我会把你已有的令牌获取代码和上传HTML文件的逻辑整合起来,给你完整的可运行示例:
你需要先准备几个额外参数:
organization:你的Azure DevOps组织名称project:目标项目名称html_file_path:本地HTML文件的路径
完整代码如下:
import requests # 替换为你的Azure AD和DevOps信息 tenant_id = 'tenant-id' client_id = 'client-id' client_secret = 'client-secret' organization = 'your-org-name' project = 'your-project-name' html_file_path = './example.html' # 1. 获取Bearer令牌 token_url = f'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token' token_data = { 'client_id': client_id, 'scope': '499b84ac-1321-427f-aa17-267ca6975798/.default', 'client_secret': client_secret, 'grant_type': 'client_credentials' } response = requests.post(token_url, data=token_data) if response.status_code != 200: print(f"获取令牌失败,状态码:{response.status_code}") print(response.text) exit() bearer_token = response.json().get('access_token') print("令牌获取成功") # 2. 读取HTML文件内容 try: with open(html_file_path, 'r', encoding='utf-8') as f: html_content = f.read() except FileNotFoundError: print(f"未找到文件:{html_file_path}") exit() # 3. 上传附件到Azure DevOps upload_url = f'https://dev.azure.com/{organization}/{project}/_apis/wit/attachments?fileName={html_file_path.split("/")[-1]}&api-version=7.0' headers = { 'Authorization': f'Bearer {bearer_token}', 'Content-Type': 'text/html', 'Accept': 'application/json' } upload_response = requests.put(upload_url, headers=headers, data=html_content) if upload_response.status_code == 201: attachment_info = upload_response.json() print(f"附件上传成功!附件URL:{attachment_info['url']}") print(f"附件ID:{attachment_info['id']}") else: print(f"上传失败,状态码:{upload_response.status_code}") print(upload_response.text)
代码说明:
- 上传请求用PUT方法,这是Azure DevOps附件API针对文本类文件直接上传的要求。
fileName参数放在URL中,用来指定附件在工作项中显示的文件名。- 读取文件时用
utf-8编码,避免中文或特殊字符出现乱码问题。 - 上传成功后,API会返回附件的
url和id,你可以用这个id调用工作项更新API,将附件关联到具体工作项。
如果需要关联到工作项,可调用工作项更新API,在请求体中添加如下内容:
[ { "op": "add", "path": "/relations/-", "value": { "rel": "AttachedFile", "url": "附件的URL", "attributes": { "name": "文件名.html" } } } ]
备注:内容来源于stack exchange,提问作者Oliver
相关产品推荐
相关产品推荐

