使用GitHub的API實(shí)現(xiàn)文件上傳--李渣渣(lizaza.cn)
https://www.bbsmax.com/A/RnJWy4lgdq/復(fù)制代碼- import requests
- import base64
- import json
-
- # 讀取文件
- def open_file(file_path):
- with open(file_path, 'wb+') as f:
- return f.read()
-
- # 將文件轉(zhuǎn)換為base64編碼,上傳文件必須將文件以base64格式上傳
- def file_base64(data):
- data_b64 = base64.b64encode(data).decode('utf-8')
- return data_b64
-
- # 上傳文件
- def upload_file(file_data):
- file_name = "" #文件名
- token = "[token]"
- url = "https://api.github.com/repos/[user]/[repo]/contents/[path]/"+file_name # 用戶名、庫(kù)名、路徑
- headers = {"Authorization": "token " + token}
- content = file_base64(file_data)
- data = {
- "message": "message",
- "committer": {
- "name": "[user]",
- "email": "user@163.com"
- },
- "content": content
- }
- data = json.dumps(data)
- req = requests.put(url=url, data=data, headers=headers)
- req.encoding = "utf-8"
- re_data = json.loads(req.text)
- print(re_data)
- print(re_data['content']['sha'])
- print("https://cdn.jsdelivr.net/gh/[user]/[repo]/[path]"+file_name)
- # 在國(guó)內(nèi)默認(rèn)的down_url可能會(huì)無(wú)法訪問(wèn),因此使用CDN訪問(wèn)
-
- if __name__ == '__main__':
- fdata = open_file('cloud.jpg')
- upload_file(fdata)
|