main.py 3.2 KB

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