Blog Webhook 自动发布

nxdong July 16, 2022 [Blog]

bolg 提交后自动发布

生成/添加部署公钥

ssh-keygen -t ed25519 -C "nxdong@nxdong.com"
cat ~/.ssh/id_ed25519.pub
# 在网站上添加部署公钥
# https://gitee.com/nxdong/nxdong.com/deploy_keys
ssh -T git@gitee.com

安装依赖

pip3 install pip --upgrade
pip3 install fastapi
pip3 install "uvicorn[standard]"
# pip3 install "uvicorn[standard]" --ignore-installed PyYAML

snap install --edge zola

程序代码

from typing import Union
from fastapi import FastAPI
from fastapi import Request
import os

# 下载项目代码的路径.需要提前手动把项目下载好
web_git = '/root/webhook/nxdong.com'
# webhook的验证key,需要与网站上的一致
webhook_auth = 'xxxxxxxx'
# nginx的部署目录, 需要与nginx的配置一致.
target = '/root/nginx/html/public'

app = FastAPI()

@app.post("/gitee/push")
async def gitee_push(req: Request):
    # print("info: headers: ", req.headers['x-gitee-token'])
    # print("info: headers: ", req.headers['X-Gitee-Event'])
    if req.headers['x-gitee-token'] != webhook_auth:
        return {'status': 'Bad Auth'}
    if req.headers['X-Gitee-Event'] != 'Push Hook':
        return {'status': 'Bad Event'}
    os.chdir(web_git)
    os.system("git fetch origin master")
    os.system("git checkout origin/master --force")
    os.system("echo y | zola build -o {}".format(target))
    return {"status": "OK"}

启动程序

# 后台启动程序
nohup uvicorn main:app --host 0.0.0.0 > ./log.txt &
# 关闭程序
# 查找pid, 发送停止信号
ps -aux | grep uvicorn
kill -9 your-pid

参考

gitee webhook