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

如何用Python Requests更新GitHub仓库文件?解决422及序列化错误

解决用Python Requests更新GitHub txt文件的两类问题

问题1:返回422错误

GitHub API要求更新文件时,content字段必须是base64编码的字符串,你直接传入明文"blah"不符合接口要求,这是导致422错误的核心原因,和author字段无关。

问题2:TypeError: Object of type bytes is not JSON serializable

base64.b64encode()返回的是bytes类型数据,JSON序列化时无法处理bytes对象,需要转成utf-8编码的字符串。

修复后的完整代码

import requests
import base64

user = "你的GitHub用户名"
repo = "你的仓库名"
token = "你的GitHub访问令牌"
file_path = "text.txt"
sha = "文件当前的SHA值"  # 需先通过GET接口获取文件最新SHA
name = "你的名字"
email = "你的邮箱"

# 处理内容编码:明文转base64字符串
content_str = "blah"
content_base64 = base64.b64encode(content_str.encode("utf-8")).decode("utf-8")

payload = {
    "message": "update text.txt",
    "content": content_base64,
    "sha": sha,
    "author": {
        "name": name,
        "email": email
    }
}

# 发送请求,用json参数自动处理序列化
url = f"https://api.github.com/repos/{user}/{repo}/contents/{file_path}"
response = requests.put(url, auth=(user, token), json=payload)
print(response.status_code)
print(response.json())  # 打印响应内容方便排查

关键注意点

  • sha必须是文件的最新SHA值,可通过GET /repos/{user}/{repo}/contents/{file_path}接口获取,否则会返回409冲突错误。
  • 使用requests.put的json参数替代手动json.dumps,requests会自动处理JSON序列化并设置正确的Content-Type请求头,减少手动处理的出错概率。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 06:01:01