40 lines
1.5 KiB
Python
40 lines
1.5 KiB
Python
|
|
from fastapi import FastAPI, HTTPException
|
||
|
|
from pydantic import BaseModel
|
||
|
|
from fastapi.staticfiles import StaticFiles
|
||
|
|
from fastapi.responses import HTMLResponse
|
||
|
|
from typing import Optional, Dict, Any
|
||
|
|
import uvicorn
|
||
|
|
from callback import call_action
|
||
|
|
from fastapi.responses import JSONResponse
|
||
|
|
|
||
|
|
app = FastAPI()
|
||
|
|
|
||
|
|
# Static files & UI server
|
||
|
|
app.mount("/static", StaticFiles(directory="static"), name="static")
|
||
|
|
|
||
|
|
class ActionArgs(BaseModel):
|
||
|
|
args: Optional[Dict[str, Any]] = None
|
||
|
|
|
||
|
|
# Show main page
|
||
|
|
@app.get("/")
|
||
|
|
async def read_index():
|
||
|
|
with open("static/index.html", "r", encoding="utf-8") as f:
|
||
|
|
html_content = f.read()
|
||
|
|
return HTMLResponse(content=html_content, status_code=200)
|
||
|
|
|
||
|
|
# Process actions via POST
|
||
|
|
@app.post("/action/{name:path}")
|
||
|
|
async def handle_action(name: str, action_args: ActionArgs):
|
||
|
|
try:
|
||
|
|
# Вызываем функцию из callback.py, передавая имя действия и аргументы
|
||
|
|
result = await call_action(name, action_args.args or {})
|
||
|
|
return JSONResponse(content={"status": "success", "result": result, "command": name})
|
||
|
|
except ValueError as e:
|
||
|
|
# Если функция не найдена, возвращаем 404
|
||
|
|
raise HTTPException(status_code=404, detail=str(e))
|
||
|
|
except Exception as e:
|
||
|
|
# Обработка остальных ошибок
|
||
|
|
raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
|
||
|
|
|
||
|
|
|
||
|
|
uvicorn.run(app, host="0.0.0.0", port=8000)
|