如何用Python的InteractiveBrowserCredential连接Azure DevOps读取拉取请求?
使用InteractiveBrowserCredential访问Azure DevOps Python API读取拉取请求
问题修复要点
你的代码存在两处关键问题:
- 调用
get_token()时未传入正确的Azure DevOps资源标识符 - 未按
Connection类要求的格式包装令牌
正确实现代码
from azure.devops.connection import Connection from azure.identity import InteractiveBrowserCredential from msrest.authentication import BasicAuthentication # 初始化交互式浏览器凭据 credential = InteractiveBrowserCredential() # 获取Azure DevOps专属令牌,资源标识符固定为https://dev.azure.com/ token = credential.get_token("https://dev.azure.com/") # 创建连接,用BasicAuthentication封装令牌(用户名留空) conn = Connection( base_url="https://dev.azure.com/你的组织名/", creds=BasicAuthentication("", token.token) ) # 获取Git客户端实例 git_client = conn.clients.get_git_client() # 读取指定项目和仓库的拉取请求 # 注意:第一个参数是项目名称,第二个是仓库名称/ID pull_requests = git_client.get_pull_requests( project="你的项目名", repository_id="my-test-repo" ) # 遍历输出拉取请求信息 for pr in pull_requests: print(f"PR ID: {pr.pull_request_id}, 标题: {pr.title}, 状态: {pr.status}")
权限错误排查方案
如果仍出现权限报错,按以下步骤检查:
- 确认登录账号在目标Azure DevOps组织中拥有读取拉取请求的权限(至少为项目贡献者角色)
- 核对组织URL、项目名、仓库名称是否完全匹配
- 交互式令牌有有效期限制,过期后需重新登录获取
内容的提问来源于stack exchange,提问作者kevinpeterson
相关产品推荐
相关产品推荐

