# -*- coding: utf-8 -*- """POUCHLAB 后端入口:API + 静态站点同源服务。 本地开发: cd server && .venv/bin/uvicorn main:app --port 8080 环境变量:PL_DB_HOST/PORT/USER/PASSWORD/NAME、PL_REDIS_URL、 PL_SMTP_HOST/PORT/USER/PASSWORD/FROM(邮件,未配置则存档模式) 生产(容器内): uvicorn main:app --host 0.0.0.0 --port 8080 """ import os from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from fastapi.responses import PlainTextResponse from fastapi.staticfiles import StaticFiles import cache import db from routes_admin import router as admin_router from routes_auth import router as auth_router from routes_agent import router as agent_router from routes_ai import router as ai_router from routes_factory import router as factory_router from routes_orders import router as orders_router app = FastAPI(title="POUCHLAB API", version="1.8.18") # 生产为同源(本服务同时托管静态站点),CORS 仅方便本地分离调试 app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=False, allow_methods=["*"], allow_headers=["*"], ) @app.middleware("http") async def no_store_html(request, call_next): """HTML/CSS/JS 永不缓存(防旧页面引用旧版本 js);图片等静态资源靠 ?v= 版本号刷新。""" response = await call_next(request) ctype = response.headers.get("content-type", "") if "text/html" in ctype or "text/css" in ctype or "javascript" in ctype: response.headers["Cache-Control"] = "no-store" return response app.include_router(auth_router) app.include_router(orders_router) app.include_router(admin_router) app.include_router(factory_router) app.include_router(ai_router) app.include_router(agent_router) @app.on_event("startup") def startup(): db.init_db() @app.get("/healthz", response_class=PlainTextResponse) def healthz(): return "ok\n" @app.get("/api/version") def version(): redis_ok = False try: redis_ok = bool(cache.client().ping()) except Exception: redis_ok = False return {"version": "1.8.18", "db": "mysql", "redis": redis_ok} # 静态站点(注册在 API 路由之后,不会遮蔽 /api) SITE_DIR = os.environ.get("PL_SITE_DIR") or os.path.join( os.path.dirname(os.path.abspath(__file__)), ".." ) if os.path.isdir(SITE_DIR): app.mount("/", StaticFiles(directory=SITE_DIR, html=True), name="site")