How to create(update) file in GitHub repo using GitHub API and Python requests?

两盒软妹~` 提交于 2019-12-11 07:32:54

问题


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())

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

If I try to do this:

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())         

I get

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

How to solve that issue?


回答1:


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())


来源:https://stackoverflow.com/questions/55663379/how-to-createupdate-file-in-github-repo-using-github-api-and-python-requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!