49 lines
1.6 KiB
Python
49 lines
1.6 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()
|
|
|
|
|
|
@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")
|