main.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. """POUCHLAB 后端入口:API + 静态站点同源服务。
  3. 本地开发:
  4. cd server && .venv/bin/uvicorn main:app --port 8080
  5. 环境变量:PL_DB_HOST/PORT/USER/PASSWORD/NAME、PL_REDIS_URL、
  6. PL_SMTP_HOST/PORT/USER/PASSWORD/FROM(邮件,未配置则存档模式)
  7. 生产(容器内):
  8. uvicorn main:app --host 0.0.0.0 --port 8080
  9. """
  10. import os
  11. from fastapi import FastAPI
  12. from fastapi.middleware.cors import CORSMiddleware
  13. from fastapi.responses import PlainTextResponse
  14. from fastapi.staticfiles import StaticFiles
  15. import cache
  16. import db
  17. from routes_admin import router as admin_router
  18. from routes_auth import router as auth_router
  19. from routes_agent import router as agent_router
  20. from routes_ai import router as ai_router
  21. from routes_factory import router as factory_router
  22. from routes_orders import router as orders_router
  23. app = FastAPI(title="POUCHLAB API", version="1.8.18")
  24. # 生产为同源(本服务同时托管静态站点),CORS 仅方便本地分离调试
  25. app.add_middleware(
  26. CORSMiddleware,
  27. allow_origins=["*"],
  28. allow_credentials=False,
  29. allow_methods=["*"],
  30. allow_headers=["*"],
  31. )
  32. @app.middleware("http")
  33. async def no_store_html(request, call_next):
  34. """HTML/CSS/JS 永不缓存(防旧页面引用旧版本 js);图片等静态资源靠 ?v= 版本号刷新。"""
  35. response = await call_next(request)
  36. ctype = response.headers.get("content-type", "")
  37. if "text/html" in ctype or "text/css" in ctype or "javascript" in ctype:
  38. response.headers["Cache-Control"] = "no-store"
  39. return response
  40. app.include_router(auth_router)
  41. app.include_router(orders_router)
  42. app.include_router(admin_router)
  43. app.include_router(factory_router)
  44. app.include_router(ai_router)
  45. app.include_router(agent_router)
  46. @app.on_event("startup")
  47. def startup():
  48. db.init_db()
  49. @app.get("/healthz", response_class=PlainTextResponse)
  50. def healthz():
  51. return "ok\n"
  52. @app.get("/api/version")
  53. def version():
  54. redis_ok = False
  55. try:
  56. redis_ok = bool(cache.client().ping())
  57. except Exception:
  58. redis_ok = False
  59. return {"version": "1.8.18", "db": "mysql", "redis": redis_ok}
  60. # 静态站点(注册在 API 路由之后,不会遮蔽 /api)
  61. SITE_DIR = os.environ.get("PL_SITE_DIR") or os.path.join(
  62. os.path.dirname(os.path.abspath(__file__)), ".."
  63. )
  64. if os.path.isdir(SITE_DIR):
  65. app.mount("/", StaticFiles(directory=SITE_DIR, html=True), name="site")