| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899 |
- # -*- 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_RESEND_API_KEY(Resend 邮件,优先)、PL_MAIL_FROM(默认 mail@steadypackaging.com)、
- PL_SMTP_HOST/PORT/USER/PASSWORD/FROM(SMTP 回退,均未配置则存档模式)
- 生产(容器内):
- uvicorn main:app --host 0.0.0.0 --port 8080
- """
- import os
- from fastapi import FastAPI, Response
- from fastapi.middleware.cors import CORSMiddleware
- from fastapi.responses import PlainTextResponse
- from fastapi.staticfiles import StaticFiles
- import cache
- import db
- import i18n
- 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.23")
- # 生产为同源(本服务同时托管静态站点),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.middleware("http")
- async def translate_api_errors(request, call_next):
- """按 Accept-Language 把 JSON API 响应里的中文提示翻译成英文。"""
- response = await call_next(request)
- ctype = response.headers.get("content-type", "")
- if "application/json" not in ctype or i18n.get_lang(request) != "en":
- return response
- body = b""
- async for chunk in response.body_iterator:
- body += chunk
- body = i18n.translate_json_body(body, "en")
- headers = dict(response.headers)
- headers.pop("content-length", None)
- return Response(content=body, status_code=response.status_code, headers=headers, media_type=ctype)
- 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.23", "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")
|