66 lines
3.1 KiB
Python
66 lines
3.1 KiB
Python
from flask import Flask, request, render_template, jsonify # 使用 jsonify 工具函数响应JSON
|
||
from loguru import logger
|
||
from config.config import GLOBAL_VAR
|
||
|
||
app = Flask(__name__)
|
||
|
||
|
||
@app.route('/') # /表示网站的根路径,在浏览器窗口输入 ip:port/ 进行访问
|
||
def welcome():
|
||
return render_template('index.html')
|
||
|
||
|
||
# @app.route('/mybot', methods=['GET','POST']), 表示同时支持GET和POST,
|
||
@app.route('/mybot', methods=['GET', 'POST'])
|
||
def get_code_webhook():
|
||
try:
|
||
logger.debug(f"fullpath: {request.full_path}")
|
||
# 如果POST数据是form格式,解析POST数据:request.form, 例如:request.form.get('name')
|
||
# 如果POST的数据是JSON格式,request.json会自动将json数据转换成Python类型(字典或者列表)
|
||
payload = request.json
|
||
logger.info(f"获取webhook信息-请求内容:{type(payload)}|| {payload}")
|
||
# 从地址中获取bot_installer_id
|
||
bot_installer_id = dict(request.args).get("installer_id")
|
||
logger.info(f"获取webhook信息-地址栏参数:{type(bot_installer_id)}|| {bot_installer_id}")
|
||
if "commits" in payload.keys():
|
||
logger.info("---------request.json中存在commits---------")
|
||
# 根据webhook请求内容 获取仓库的名称
|
||
repository = payload.get("repository")
|
||
project = repository.get("full_name")
|
||
# 根据webhook请求内容 获取本次推送的分支
|
||
branch = payload.get("ref").split("/")[-1]
|
||
# 根据webhook请求内容,获取当次push过来的commits信息
|
||
commits = payload.get("commits")
|
||
# 根据commits信息获取每次提交的message
|
||
commits_info = []
|
||
for commit in commits:
|
||
commits_info.append(
|
||
f"{commit['author']['name']}/{commit['author']['email']} 于 {commit['timestamp']} 在分支 {branch} 提交了代码。 "
|
||
f"commit_id是{commit['id'][:10]} || commit内容是:{commit['message']}")
|
||
# 收集这些关键信息作为全局变量,留待定时任务处理时需要
|
||
if project not in GLOBAL_VAR:
|
||
GLOBAL_VAR[project] = {}
|
||
GLOBAL_VAR[project]["commits"] = {}
|
||
if branch not in GLOBAL_VAR[project]["commits"]:
|
||
GLOBAL_VAR[project]["commits"][branch] = []
|
||
GLOBAL_VAR[project]["commits"][branch].extend(commits_info)
|
||
GLOBAL_VAR[project]["bot_installer_id"] = bot_installer_id
|
||
logger.debug(f"从服务获取的全局变量:{type(GLOBAL_VAR)}|| {GLOBAL_VAR}")
|
||
result = jsonify({
|
||
"code": 0,
|
||
"msg": "success",
|
||
"payload": request.json,
|
||
"installer_id": bot_installer_id
|
||
})
|
||
else:
|
||
result = jsonify({
|
||
"code": 1,
|
||
"msg": "没有检测到commits信息,bot无法进行处理",
|
||
})
|
||
except Exception as e:
|
||
result = jsonify({
|
||
"code": -1,
|
||
"msg": "exception:" + str(e)
|
||
})
|
||
return result
|