想使用github token创建一个一条龙的服务,那就是创建仓库,添加index文件, 并发布github page页面,就需要对全流程的api有了解,今天我操作了一番,记录一下流程。
第一步,创建仓库的API
先创建一个仓库:
import requests
import json
url = "https://api.github.com/user/repos"
payload = json.dumps({
"name": "仓库名称",
"description": "This is your first repo!",
"homepage": "https: //github.com",
"private": False
})
headers = {
'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)',
'Content-Type': 'application/json',
'Authorization': 'Bearer 你自己的token'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
发送完请求之后,就会出现一个仓库,我这里用的HelloWorld仓库名:
第二步,添加一个index.html
创建一个index.html页面,用于github page页面使用。先创建一个简单地html页面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Github page</title>
</head>
<body>
这是Github page页面
</body>
</html>
然后用python发送请求上传:
import base64
import json
import requests
def read_file(file_path):
with open(file_path, "rb+") as f:
return f.read()
def add_file(path, content, message):
url = f"https://api.github.com/repos/用户名/仓库名/{path}"
GIT_TOKEN = 你的token
headers = {"Authorization": f"Bearer {GIT_TOKEN}",
'Accept': 'application/vnd.github.v3+json',
'Content-Type': 'application/json'}
base64_content = base64.b64encode(content).decode('utf-8')
payload = json.dumps({
"message": message,
"branch": "gh-pages",
"content": base64_content
})
print("开始推送文件....")
response = requests.request("PUT", url, headers=headers, data=payload)
print(response.text)
if __name__ == '__main__':
file = read_file("index.html")
add_file("index.html", file, "添加文件")
上传完成之后,就会在仓库看大这个文件:
第三步,发布github page
开始发布github page页面,branch一般写main,path表示你的index.html页面的路径,/表示根目录:
import requests
import json
url = "https://api.github.com/repos/用户名/仓库名/pages"
payload = json.dumps({
"source": {
"branch": "分支",
"path": "/"
}
})
headers = {
'User-Agent': 'Apifox/1.0.0 (https://www.apifox.cn)',
'Content-Type': 'application/json',
'Authorization': 'Bearer 你的token'
}
response = requests.request("POST", url, headers=headers, data=payload)
print(response.text)
请求发送完之后,返回的响应里面,就有你的github page页面地址:
直接访问,就可以看到你的index.html页面内容: