58 lines
2.2 KiB
Python
58 lines
2.2 KiB
Python
from fastapi import FastAPI, Request
|
||
from fastapi.responses import FileResponse, JSONResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
|
||
from .db.session import init_db
|
||
from .api.routers import auth, admin, channels, characters, chat, extra
|
||
from .api import v1
|
||
|
||
app = FastAPI(title="Open Maopaoya", docs_url="/api/docs", openapi_url="/api/openapi.json")
|
||
|
||
# 性能:响应压缩
|
||
from starlette.middleware.gzip import GZipMiddleware
|
||
app.add_middleware(GZipMiddleware, minimum_size=1024)
|
||
|
||
# API 路由(/v1 为商业化稳定契约,独立前缀不随 /api 演进)
|
||
app.include_router(v1.router)
|
||
|
||
for r in (auth.router, admin.router, channels.router, characters.router,
|
||
chat.router, extra.router):
|
||
app.include_router(r, prefix="/api")
|
||
|
||
|
||
@app.on_event("startup")
|
||
async def startup():
|
||
await init_db()
|
||
# 首个管理员
|
||
from .db.session import SessionLocal
|
||
from .db import repos
|
||
from .models.entities import User
|
||
from .core import security
|
||
from .core.config import settings
|
||
import os
|
||
async with SessionLocal() as db:
|
||
users = await repos.UserRepo.all(db)
|
||
if not users:
|
||
salt = os.urandom(16)
|
||
db.add(User(username=settings.first_admin_user,
|
||
password_hash=security.hash_password(settings.first_admin_pass),
|
||
kdf_salt=salt.hex(), is_admin=True))
|
||
await db.commit()
|
||
# 默认渠道:空库时种 Step Plan 预设(key 走 OMO_STEP_API_KEY)
|
||
from .models.entities import Channel
|
||
from .core.config import STEP_PRESET
|
||
chans = (await db.execute(__import__('sqlalchemy').select(Channel))).scalars().all()
|
||
if not chans:
|
||
db.add(Channel(name=STEP_PRESET["name"], base_url=STEP_PRESET["base_url"],
|
||
api_key_enc=settings.step_api_key, models=STEP_PRESET["models"],
|
||
owner_id=None, visibility="admin"))
|
||
await db.commit()
|
||
|
||
|
||
@app.exception_handler(Exception)
|
||
async def error_handler(request: Request, exc: Exception):
|
||
return JSONResponse(status_code=500, content={"detail": str(exc)[:300]})
|
||
|
||
|
||
app.mount("/", StaticFiles(directory="web", html=True), name="web")
|