Files
NqiTools/backend/app/main.py
T

85 lines
2.3 KiB
Python

"""本机接口。只监听 127.0.0.1。功能路由按目录挂上。"""
import asyncio
import logging
import sys
from contextlib import asynccontextmanager, suppress
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from app.features.download.router import router as download_router
from app.platform.auth import router as auth_router
from app.platform.keepalive import session_keepalive
from app.shared.state import state
ORIGINS = [
"http://localhost:1420",
"http://127.0.0.1:1420",
"tauri://localhost",
"http://tauri.localhost",
"https://tauri.localhost",
]
def configure_logging() -> None:
"""让 nqi.* 的 INFO 写到标准输出。uvicorn 默认不接管这个记录器。"""
nqi = logging.getLogger("nqi")
nqi.setLevel(logging.INFO)
if not any(getattr(handler, "_nqi_stdout", False) for handler in nqi.handlers):
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s: %(message)s"))
handler._nqi_stdout = True
nqi.addHandler(handler)
nqi.propagate = False
@asynccontextmanager
async def lifespan(_app: FastAPI):
configure_logging()
keepalive = asyncio.create_task(session_keepalive())
try:
yield
finally:
keepalive.cancel()
with suppress(asyncio.CancelledError):
await keepalive
if state.client is not None:
await state.client.aclose()
for client, _challenge in state.flows.values():
await client.aclose()
app = FastAPI(title="NqiTools", lifespan=lifespan)
app.add_middleware(
CORSMiddleware,
allow_origins=ORIGINS,
allow_credentials=False,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(auth_router)
app.include_router(download_router)
@app.get("/api/health")
async def health() -> dict:
return {"ok": True}
if __name__ == "__main__":
import os
import socket
import uvicorn
configure_logging()
chosen = os.environ.get("NQI_PORT")
if chosen:
port = int(chosen)
else:
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
uvicorn.run("app.main:app", host="127.0.0.1", port=port)