如何使用GitHub API和Python请求在GitHub存储库中创建(更新)文件? [英] How to create(update) file in GitHub repo using GitHub API and Python requests?

查看:246
本文介绍了如何使用GitHub API和Python请求在GitHub存储库中创建(更新)文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用python在GitHub公共仓库中创建一个新文件. 当我尝试执行此操作时:

I'm creating a new file in GitHub public repo using python. When I try to do this:

import json
import requests

with open('README.md', 'r') as f:
    content = f.read()
    payload = {"message": "Add text.txt",
               "author": {"name": name,"email": email},
               "content": content}
    result = requests.put("https://api.github.com/repos/<GitHubLogin>/<Repo>/contents/README.md", 
                           auth=(name, password), 
                           json=payload)
    print(result.json())

我收到"{'message':'内容无效的Base64',....}"

I get "{'message': 'content is not valid Base64', ....}"

如果我尝试这样做:

import base64 
import json
import requests

with open('README.md', 'r') as f:
    content = f.read()
    content = bytes(content, "utf-8")
    contnet = base64.b64encode(content)
    payload = {"message": "Add text.txt",
               "author": {"name": name,"email": email},
               "content": content}
    result = requests.put("https://api.github.com/repos/<GitHubLogin>/<Repo>/contents/README.md", 
                          auth=(name, password), 
                          json=payload)
    print(result.json())         

我知道

Traceback (most recent call last)
     19     result = requests.put("https://api.github.com/repos/VadymKhodak/tester/contents/README.md", 
     20                           auth=(name, password),
---> 21                           json=payload)

TypeError: Object of type 'bytes' is not JSON serializable

如何解决该问题?

推荐答案

我解决了这个问题!!!

I solve this issue!!!

ENCODING = 'utf-8'
with open('README.md', 'rb') as f:
    byte_content = f.read()
    base64_bytes = base64.b64encode(byte_content)
    base64_string = base64_bytes.decode(ENCODING)
    payload = {"message": "Add text.txt",
               "author": {"name": name,"email": email},
               "content": base64_string}
    result = requests.put("https://api.github.com/repos/<GitHubLogin>/<Repo>/contents/README.md", 
                          auth=(name, password), 
                          json=payload)
    print(result.json())

这篇关于如何使用GitHub API和Python请求在GitHub存储库中创建(更新)文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆