main.py 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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, Response
  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. import i18n
  18. from routes_admin import router as admin_router
  19. from routes_auth import router as auth_router
  20. from routes_agent import router as agent_router
  21. from routes_ai import router as ai_router
  22. from routes_factory import router as factory_router
  23. from routes_orders import router as orders_router
  24. app = FastAPI(title="POUCHLAB API", version="1.8.18")
  25. # 生产为同源(本服务同时托管静态站点),CORS 仅方便本地分离调试
  26. app.add_middleware(
  27. CORSMiddleware,
  28. allow_origins=["*"],
  29. allow_credentials=False,
  30. allow_methods=["*"],
  31. allow_headers=["*"],
  32. )
  33. @app.middleware("http")
  34. async def no_store_html(request, call_next):
  35. """HTML/CSS/JS 永不缓存(防旧页面引用旧版本 js);图片等静态资源靠 ?v= 版本号刷新。"""
  36. response = await call_next(request)
  37. ctype = response.headers.get("content-type", "")
  38. if "text/html" in ctype or "text/css" in ctype or "javascript" in ctype:
  39. response.headers["Cache-Control"] = "no-store"
  40. return response
  41. @app.middleware("http")
  42. async def translate_api_errors(request, call_next):
  43. """按 Accept-Language 把 JSON API 响应里的中文提示翻译成英文。"""
  44. response = await call_next(request)
  45. ctype = response.headers.get("content-type", "")
  46. if "application/json" not in ctype or i18n.get_lang(request) != "en":
  47. return response
  48. body = b""
  49. async for chunk in response.body_iterator:
  50. body += chunk
  51. body = i18n.translate_json_body(body, "en")
  52. headers = dict(response.headers)
  53. headers.pop("content-length", None)
  54. return Response(content=body, status_code=response.status_code, headers=headers, media_type=ctype)
  55. app.include_router(auth_router)
  56. app.include_router(orders_router)
  57. app.include_router(admin_router)
  58. app.include_router(factory_router)
  59. app.include_router(ai_router)
  60. app.include_router(agent_router)
  61. @app.on_event("startup")
  62. def startup():
  63. db.init_db()
  64. @app.get("/healthz", response_class=PlainTextResponse)
  65. def healthz():
  66. return "ok\n"
  67. @app.get("/api/version")
  68. def version():
  69. redis_ok = False
  70. try:
  71. redis_ok = bool(cache.client().ping())
  72. except Exception:
  73. redis_ok = False
  74. return {"version": "1.8.18", "db": "mysql", "redis": redis_ok}
  75. # 静态站点(注册在 API 路由之后,不会遮蔽 /api)
  76. SITE_DIR = os.environ.get("PL_SITE_DIR") or os.path.join(
  77. os.path.dirname(os.path.abspath(__file__)), ".."
  78. )
  79. if os.path.isdir(SITE_DIR):
  80. app.mount("/", StaticFiles(directory=SITE_DIR, html=True), name="site")