refactor: 优化后端数据库与依赖

- 优化 api/database/database.py
- 更新 api/requirements.txt

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
iammm0
2026-02-12 13:33:14 +08:00
parent d817b6eac5
commit a261d9da27
2 changed files with 14 additions and 36 deletions

View File

@@ -1,6 +1,6 @@
""" """
数据库连接和初始化 数据库连接和初始化
支持 PostgreSQL(推荐)和 SQLite本地开发 支持 PostgreSQL
""" """
import os import os
from sqlalchemy import create_engine from sqlalchemy import create_engine
@@ -20,25 +20,14 @@ def parse_database_url(url: str) -> tuple[str, str]:
支持格式: 支持格式:
- PostgreSQL: postgresql://user:pass@host:port/db - PostgreSQL: postgresql://user:pass@host:port/db
- PostgreSQL async: postgresql+asyncpg://user:pass@host:port/db - PostgreSQL async: postgresql+asyncpg://user:pass@host:port/db
- SQLite: sqlite:///./path/to/db.db
- SQLite async: sqlite+aiosqlite:///./path/to/db.db
""" """
# PostgreSQL
if url.startswith("postgresql+asyncpg://"): if url.startswith("postgresql+asyncpg://"):
async_url = url async_url = url
sync_url = url.replace("postgresql+asyncpg://", "postgresql://") sync_url = url.replace("postgresql+asyncpg://", "postgresql://")
elif url.startswith("postgresql://"): elif url.startswith("postgresql://"):
sync_url = url sync_url = url
async_url = url.replace("postgresql://", "postgresql+asyncpg://") async_url = url.replace("postgresql://", "postgresql+asyncpg://")
# SQLite
elif url.startswith("sqlite+aiosqlite://"):
async_url = url
sync_url = url.replace("sqlite+aiosqlite://", "sqlite://")
elif url.startswith("sqlite://"):
sync_url = url
async_url = url.replace("sqlite://", "sqlite+aiosqlite://")
else: else:
# 默认使用 PostgreSQL
print(f"警告: DATABASE_URL 格式不正确 ({url}),使用默认 PostgreSQL") print(f"警告: DATABASE_URL 格式不正确 ({url}),使用默认 PostgreSQL")
sync_url = "postgresql://postgres:postgres@localhost:5432/life_echo" sync_url = "postgresql://postgres:postgres@localhost:5432/life_echo"
async_url = "postgresql+asyncpg://postgres:postgres@localhost:5432/life_echo" async_url = "postgresql+asyncpg://postgres:postgres@localhost:5432/life_echo"
@@ -48,27 +37,19 @@ def parse_database_url(url: str) -> tuple[str, str]:
DATABASE_URL, ASYNC_DATABASE_URL = parse_database_url(raw_database_url) DATABASE_URL, ASYNC_DATABASE_URL = parse_database_url(raw_database_url)
# 创建同步引擎用于迁移、Celery 任务等) # 同步引擎用于迁移、Celery 任务等),使用 psycopg
# SQLite 需要特殊的 connect_args
if DATABASE_URL.startswith("sqlite"):
engine = create_engine(DATABASE_URL, connect_args={"check_same_thread": False})
else:
# 使用 psycopg (v3) 驱动
sync_url = DATABASE_URL.replace("postgresql://", "postgresql+psycopg://") sync_url = DATABASE_URL.replace("postgresql://", "postgresql+psycopg://")
engine = create_engine(sync_url, pool_size=5, max_overflow=10) engine = create_engine(sync_url, pool_size=5, max_overflow=10)
# 创建异步引擎(用于 FastAPI # 异步引擎(用于 FastAPI
if ASYNC_DATABASE_URL.startswith("sqlite"):
async_engine = create_async_engine(ASYNC_DATABASE_URL, echo=False)
else:
async_engine = create_async_engine( async_engine = create_async_engine(
ASYNC_DATABASE_URL, ASYNC_DATABASE_URL,
echo=False, echo=False,
pool_size=5, pool_size=5,
max_overflow=10 max_overflow=10,
) )
# 创建会话工厂 # 会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
AsyncSessionLocal = async_sessionmaker(async_engine, class_=AsyncSession, expire_on_commit=False) AsyncSessionLocal = async_sessionmaker(async_engine, class_=AsyncSession, expire_on_commit=False)
@@ -98,4 +79,3 @@ async def get_async_db():
raise raise
finally: finally:
await session.close() await session.close()

View File

@@ -14,8 +14,6 @@ greenlet>=3.3.0
# PostgreSQL drivers # PostgreSQL drivers
asyncpg>=0.29.0 asyncpg>=0.29.0
psycopg[binary]>=3.1.0 psycopg[binary]>=3.1.0
# SQLite
aiosqlite==0.20.0
# Redis for session storage # Redis for session storage
redis>=5.0.0 redis>=5.0.0