问题描述
我正在尝试从 python 程序更新已创建的 json 文件。问题是,我不知道该怎么做。
我找到了 this api,我很确定这与我正在尝试做的事情有关。 我又一次不知道如何正确使用它。
我还发现了一个名为“simplegists”的 GitHub gists 包装器,它看起来非常适合我想要做的事情。但是,它目前似乎已损坏,我和其他人在使用它时遇到了问题(特别是 this problem)。
有人愿意帮助我弄清楚如何使用 GitHub 身份验证令牌在 Python 中编辑要点,或者至少给我一些我可以参考的参考资料吗?谢谢!
解决方法
由于 Github discontinued 于 2020 年 11 月 13 日对 API 进行了密码身份验证,因此相当多的 Python 包装器不再起作用。继续进行的最佳方法是使用 API 令牌。 所以首先 get a token 并选择相关范围 ('gist')。
然后您可以使用符合 API description 的 python 补丁请求来使用新的 json 文件更新您的要点:
import requests
import json
token='API_TOKEN'
filename="YOUR_UPDATED_JSON_FILE.json"
gist_id="GIST_ID"
content=open(filename,'r').read()
headers = {'Authorization': f'token {token}'}
r = requests.patch('https://api.github.com/gists/' + gist_id,data=json.dumps({'files':{filename:{"content":content}}}),headers=headers)
print(r.json())
请注意,此示例假定您尚未启用 two-factor authentication。