Files
gemini-balance/app/database/connection.py
snaily d94d24f96c feat(error_handling): 增强 API 错误处理和日志记录
- 扩展 ErrorLog 数据模型,增加 model_name, error_type, error_code 字段,以记录更详细的错误信息。
- 在 GeminiChatService 和 OpenAIChatService 中添加了 try-except 块,用于捕获 API 调用(包括普通和流式调用)时发生的异常。
- 实现从异常消息中通过正则表达式提取 HTTP 状态码的功能。
- 调用 add_error_log 服务将详细的错误信息(包括模型、错误类型、代码、请求体)持久化到数据库。
- 更新了 error_logs 前端页面,增加显示模型名称列及详情。
- 优化数据库连接池配置 (pool_recycle=3600),提高连接稳定性。
2025-04-10 15:40:02 +08:00

51 lines
1.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
数据库连接池模块
"""
from databases import Database
from sqlalchemy import create_engine, MetaData
from sqlalchemy.ext.declarative import declarative_base
from app.config.config import settings
from app.log.logger import get_database_logger
logger = get_database_logger()
# 数据库URL
DATABASE_URL = f"mysql+pymysql://{settings.MYSQL_USER}:{settings.MYSQL_PASSWORD}@{settings.MYSQL_HOST}:{settings.MYSQL_PORT}/{settings.MYSQL_DATABASE}"
# 创建数据库引擎
engine = create_engine(DATABASE_URL)
# 创建元数据对象
metadata = MetaData()
# 创建基类
Base = declarative_base(metadata=metadata)
# 创建数据库连接池,并配置连接池参数
# pool_recycle=3600: 回收空闲超过1小时的连接防止MySQL服务器超时断开
database = Database(DATABASE_URL, min_size=5, max_size=20, pool_recycle=3600)
async def connect_to_db():
"""
连接到数据库
"""
try:
await database.connect()
logger.info("Connected to database")
except Exception as e:
logger.error(f"Failed to connect to database: {str(e)}")
raise
async def disconnect_from_db():
"""
断开数据库连接
"""
try:
await database.disconnect()
logger.info("Disconnected from database")
except Exception as e:
logger.error(f"Failed to disconnect from database: {str(e)}")