s
This commit is contained in:
71
web.py
Normal file
71
web.py
Normal file
@@ -0,0 +1,71 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import FileResponse, JSONResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
# ---------------- 配置 ----------------
|
||||
BOT_NAME = "hdmi" # PM2 进程名
|
||||
BASE_DIR = Path(__file__).parent
|
||||
|
||||
# 允许前端跨域访问
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 静态文件
|
||||
app.mount("/static", StaticFiles(directory=BASE_DIR), name="static")
|
||||
|
||||
# ---------------- PM2 控制 ----------------
|
||||
def pm2_cmd(cmd: str):
|
||||
try:
|
||||
out = subprocess.check_output(f"pm2 {cmd}", shell=True, stderr=subprocess.STDOUT, text=True)
|
||||
return out
|
||||
except subprocess.CalledProcessError as e:
|
||||
return e.output
|
||||
|
||||
def read_log(log_type="out", lines=50):
|
||||
log_file = BASE_DIR.parent / f".pm2/logs/{BOT_NAME}-{log_type}.log"
|
||||
try:
|
||||
with open(log_file, "r", encoding="utf-8") as f:
|
||||
content = f.readlines()[-lines:]
|
||||
return "".join(content)
|
||||
except FileNotFoundError:
|
||||
return f"未找到日志文件: {log_file}"
|
||||
|
||||
@app.get("/start")
|
||||
def start():
|
||||
out = pm2_cmd(f"start {BOT_NAME}")
|
||||
return JSONResponse({"action": "start", "output": out})
|
||||
|
||||
@app.get("/stop")
|
||||
def stop():
|
||||
out = pm2_cmd(f"stop {BOT_NAME} --no-autorestart")
|
||||
return JSONResponse({"action": "stop", "output": out})
|
||||
|
||||
@app.get("/restart")
|
||||
def restart():
|
||||
out = pm2_cmd(f"restart {BOT_NAME}")
|
||||
return JSONResponse({"action": "restart", "output": out})
|
||||
|
||||
@app.get("/status")
|
||||
def status():
|
||||
status = pm2_cmd(f"status {BOT_NAME}")
|
||||
log = read_log("out", 50)
|
||||
error_log = read_log("error", 50)
|
||||
return JSONResponse({
|
||||
"status": status,
|
||||
"recent_log": log,
|
||||
"recent_error": error_log
|
||||
})
|
||||
|
||||
# ---------------- HTML ----------------
|
||||
@app.get("/")
|
||||
def index():
|
||||
return FileResponse(BASE_DIR / "index.html")
|
||||
Reference in New Issue
Block a user