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

Jupyter调用GitHub仓库触发BadCredentialsException错误求助

解决PyGithub调用GitHub API时的BadCredentialsException(401错误)

针对你遇到的401凭证错误,按以下步骤排查修复:

1. 修正仓库路径格式

get_repo方法必须传入owner/repo的完整格式(比如你的GitHub用户名/los-lobos),你当前代码里只写了los-lobos,GitHub无法定位到具体仓库,这是触发401错误的常见原因之一。

2. 验证PAT的有效性与权限

  • 检查PAT输入是否正确:确认没有多余空格、换行或复制遗漏字符,Jupyter中粘贴时注意是否自动添加了转义字符。
  • 确认PAT权限足够:创建PAT时必须勾选对应权限,至少需要repo权限(访问私有仓库);如果要操作Actions和分支保护,还需额外勾选workflow、admin:repo_hook等权限。
  • 手动验证PAT:用命令行测试PAT是否能正常访问API:
curl -H "Authorization: token 你的PAT内容" https://api.github.com/user

如果返回用户信息,说明PAT有效;若仍返回401,说明PAT无效或权限不足,需要重新生成。

3. 更新PyGithub到最新版本

旧版本PyGithub可能存在API兼容性问题,执行以下命令更新:

pip install --upgrade PyGithub

4. 排查网络/代理问题

如果你的环境使用代理,需要为PyGithub配置代理会话:

from github import Github
import requests

proxies = {
    "http": "http://你的代理地址:端口",
    "https": "https://你的代理地址:端口",
}
session = requests.Session()
session.proxies = proxies
g = Github('你的PAT内容', session=session)

修复后的示例代码

from github import Github

# 替换为你的有效PAT和正确的仓库路径
g = Github('your-valid-personal-access-token')
repo = g.get_repo('your-github-username/los-lobos')  # 必须是owner/repo格式

# 检查Actions权限配置
actions = repo.get_actions()
if not actions.permissions:
    print('仓库未设置Actions权限')
else:
    for action in actions.permissions:
        print(f'{action} 已配置仓库权限')

# 检查提交触发的流水线数量
pipelines = repo.get_workflows()
if not pipelines.totalCount:
    print('未配置提交触发的流水线')
else:
    print(f'已配置 {pipelines.totalCount} 条提交触发的流水线')

# 检查分支保护规则(添加异常捕获避免权限不足报错)
try:
    branch_protection = repo.get_branch_protection('main')
    if not branch_protection.restrictions:
        print('新分支未配置提交Actions')
    else:
        print('新分支已配置提交Actions')
except Exception as e:
    print(f'获取分支保护规则失败:{str(e)}')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 03:23:14