mirror of
https://github.com/vastsa/FileCodeBox.git
synced 2026-11-20 13:29:56 +08:00
perf(startup): drop duplicate Tortoise init, keep ORM exception handlers
This commit is contained in:
1 parent
496a7139bd
commit
4f141eeb49
2 files changed
+78
-11
No files matched your search
@@ -10,7 +10,7 @@ from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from tortoise import Tortoise
|
||||
from tortoise.contrib.fastapi import register_tortoise
|
||||
from tortoise.contrib.fastapi import tortoise_exception_handlers
|
||||
|
||||
from apps.admin.views import admin_api
|
||||
from apps.base.config import (
|
||||
@@ -29,7 +29,7 @@ from apps.base.tasks import (
|
||||
)
|
||||
from apps.base.views import share_api, chunk_api, presign_api
|
||||
from apps.base.mcp import router as mcp_router
|
||||
from core.database import db_startup_lock, get_db_config, init_db
|
||||
from core.database import db_startup_lock, init_db
|
||||
from core.errors import StorageError
|
||||
from core.logger import get_log_level_name, is_access_log_enabled, logger
|
||||
from core.settings import settings
|
||||
@@ -89,7 +89,14 @@ async def load_config():
|
||||
)
|
||||
|
||||
|
||||
app = FastAPI(lifespan=lifespan, version=APP_VERSION)
|
||||
# Tortoise 的 ORM 异常映射(DoesNotExist → 404、IntegrityError → 422)。
|
||||
# 只注册处理器;连接初始化统一由 lifespan 里的 init_db() 负责,
|
||||
# 避免 register_tortoise 合并 lifespan 造成的双重初始化。
|
||||
app = FastAPI(
|
||||
lifespan=lifespan,
|
||||
version=APP_VERSION,
|
||||
exception_handlers=tortoise_exception_handlers(),
|
||||
)
|
||||
|
||||
|
||||
@app.exception_handler(StorageError)
|
||||
@@ -126,14 +133,6 @@ app.add_middleware(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# 使用 register_tortoise 来添加异常处理器
|
||||
register_tortoise(
|
||||
app,
|
||||
config=get_db_config(),
|
||||
generate_schemas=False,
|
||||
add_exception_handlers=True,
|
||||
)
|
||||
|
||||
app.include_router(share_api)
|
||||
app.include_router(chunk_api)
|
||||
app.include_router(presign_api)
|
||||
|
||||
@@ -0,0 +1,68 @@
|
||||
"""One Tortoise init path; ORM exception mappings still registered."""
|
||||
import asyncio
|
||||
import unittest
|
||||
from pathlib import Path
|
||||
from unittest import mock
|
||||
|
||||
from tortoise.exceptions import DoesNotExist, IntegrityError
|
||||
|
||||
import main
|
||||
|
||||
|
||||
async def _idle_task():
|
||||
# Stand-in for the real background loops; the lifespan cancels it on exit.
|
||||
await asyncio.sleep(3600)
|
||||
|
||||
|
||||
class StartupSingleInitTests(unittest.TestCase):
|
||||
def test_orm_exception_handlers_are_registered(self):
|
||||
# Behavior pinned by test_admin_write_paths: DoesNotExist -> 404 JSON.
|
||||
# IntegrityError -> 422 must stay available too.
|
||||
self.assertIn(DoesNotExist, main.app.exception_handlers)
|
||||
self.assertIn(IntegrityError, main.app.exception_handlers)
|
||||
|
||||
def test_register_tortoise_is_not_used(self):
|
||||
# register_tortoise merges another lifespan that calls Tortoise.init
|
||||
# before init_db(); batch 4 (SQLite PRAGMAs) needs a single init path.
|
||||
source = Path("main.py").read_text(encoding="utf-8")
|
||||
self.assertNotIn("import register_tortoise", source)
|
||||
self.assertNotIn("register_tortoise(", source)
|
||||
|
||||
def test_lifespan_does_not_initialize_tortoise_outside_init_db(self):
|
||||
async def scenario():
|
||||
init_db_calls = []
|
||||
|
||||
async def fake_init_db():
|
||||
init_db_calls.append(True)
|
||||
|
||||
async def fake_load_config():
|
||||
return None
|
||||
|
||||
with (
|
||||
mock.patch.object(main, "init_db", fake_init_db),
|
||||
mock.patch.object(main, "load_config", fake_load_config),
|
||||
mock.patch.object(main, "delete_expire_files", _idle_task),
|
||||
mock.patch.object(main, "clean_incomplete_uploads", _idle_task),
|
||||
mock.patch.object(
|
||||
main, "clean_expired_presign_sessions", _idle_task
|
||||
),
|
||||
mock.patch.object(main.Tortoise, "init") as tortoise_init,
|
||||
mock.patch.object(
|
||||
main.Tortoise, "close_connections"
|
||||
),
|
||||
):
|
||||
# FastAPI merges the lifespan of every included router, so use
|
||||
# the installed context rather than main.lifespan directly.
|
||||
async with main.app.router.lifespan_context(main.app):
|
||||
pass
|
||||
|
||||
return init_db_calls, tortoise_init
|
||||
|
||||
init_db_calls, tortoise_init = asyncio.run(scenario())
|
||||
|
||||
self.assertEqual(init_db_calls, [True])
|
||||
tortoise_init.assert_not_awaited()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user