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

Github Actions中凭证正确仍触发BadCredentialsException问题求助

解决GitHub Actions中PyGitHub的BadCredentialsException问题

核心问题

你的代码里token = ""是空值,这是触发401错误的直接原因——GitHub Actions中不能硬编码Token,必须通过仓库Secrets注入有效凭证,即使你已配置Token权限,代码读取不到有效值就会验证失败。

分步修复方案

1. 确认仓库Secrets配置

进入ball-classification仓库,依次打开Settings → Secrets and variables → Actions,创建名为GH_TOKEN的仓库Secret,值填入你拥有repo全权限的GitHub Token。

2. 修改Python代码读取环境变量

替换代码中硬编码的空Token,改为从环境变量读取:

import os

# github credentials
owner = 'kmeans27'
repo_name = 'ball-classification'  # 重命名避免变量冲突
branch = 'main'
path = 'output'
# 从Actions环境变量读取Token
token = os.getenv('GH_TOKEN')

# Push changes to GitHub
g = Github(token)
repo = g.get_repo(f"{owner}/{repo_name}")
branch_obj = repo.get_branch(branch)  # 重命名避免变量冲突
file_name = "predictions.csv"
file_path = f"{path}/{file_name}"
contents = repo.get_contents(file_path, ref=branch_obj.name)
with open(csv_path, "r") as file:
    content = file.read()
if contents:
    repo.update_file(contents.path, f'Update {file_name}', content, contents.sha, branch=branch_obj.name)
else:
    repo.create_file(file_path, f'Add {file_name}', content, branch=branch_obj.name)

3. 更新GitHub Actions工作流

在执行Python脚本的步骤中注入Secret:

- name: Run prediction script
  env:
    GH_TOKEN: ${{ secrets.GH_TOKEN }}
  run: python batch_predict.py

额外检查项

  • 确认Token未过期:GitHub Token默认有效期30天,过期需重新生成
  • 精简Token权限:当前代码仅需repo权限,read:user权限可移除(除非脚本用到用户信息)
  • 避免变量名冲突:原代码中repo和branch被重复赋值,重命名后可减少潜在问题

内容的提问来源于stack exchange,提问作者Mark Müller

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 19:10:15