使用GitHub的API實現文件上傳--李渣渣(lizaza.cn)
https://www.bbsmax.com/A/RnJWy4lgdq/復制代碼- import requests
- import base64
- import json
-
- # 讀取文件
- def open_file(file_path):
- with open(file_path, 'wb+') as f:
- return f.read()
-
- # 將文件轉換為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 # 用戶名、庫名、路徑
- 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)
- # 在國內默認的down_url可能會無法訪問,因此使用CDN訪問
-
- if __name__ == '__main__':
- fdata = open_file('cloud.jpg')
- upload_file(fdata)
|