mirror of
https://github.com/snailyp/gemini-balance.git
synced 2026-09-05 15:36:45 +08:00
chore:清理代码,移除不必要的注释和导入,优化日志记录和错误处理
This commit is contained in:
+1
-11
@@ -11,13 +11,6 @@ from sqlalchemy import insert, update, select
|
|||||||
|
|
||||||
from app.core.constants import API_VERSION, DEFAULT_CREATE_IMAGE_MODEL, DEFAULT_FILTER_MODELS, DEFAULT_MODEL, DEFAULT_STREAM_CHUNK_SIZE, DEFAULT_STREAM_LONG_TEXT_THRESHOLD, DEFAULT_STREAM_MAX_DELAY, DEFAULT_STREAM_MIN_DELAY, DEFAULT_STREAM_SHORT_TEXT_THRESHOLD, DEFAULT_TIMEOUT, MAX_RETRIES
|
from app.core.constants import API_VERSION, DEFAULT_CREATE_IMAGE_MODEL, DEFAULT_FILTER_MODELS, DEFAULT_MODEL, DEFAULT_STREAM_CHUNK_SIZE, DEFAULT_STREAM_LONG_TEXT_THRESHOLD, DEFAULT_STREAM_MAX_DELAY, DEFAULT_STREAM_MIN_DELAY, DEFAULT_STREAM_SHORT_TEXT_THRESHOLD, DEFAULT_TIMEOUT, MAX_RETRIES
|
||||||
from app.log.logger import Logger
|
from app.log.logger import Logger
|
||||||
# from app.log.logger import get_config_logger # 移除顶层导入
|
|
||||||
# 延迟导入以避免循环依赖,仅在 sync_initial_settings 中使用
|
|
||||||
# from app.database.connection import database
|
|
||||||
# from app.database.models import Settings as SettingsModel
|
|
||||||
# from app.database.services import get_all_settings # get_all_settings 可能不适合启动时调用,直接查询
|
|
||||||
|
|
||||||
# logger = get_config_logger() # 移除顶层初始化
|
|
||||||
|
|
||||||
|
|
||||||
class Settings(BaseSettings):
|
class Settings(BaseSettings):
|
||||||
@@ -308,10 +301,7 @@ async def sync_initial_settings():
|
|||||||
finally:
|
finally:
|
||||||
if database.is_connected:
|
if database.is_connected:
|
||||||
try:
|
try:
|
||||||
# Don't disconnect if it's managed elsewhere (e.g., FastAPI lifespan)
|
pass
|
||||||
# await database.disconnect()
|
|
||||||
# logger.info("Database connection closed after initial sync.")
|
|
||||||
pass # Assume connection lifecycle is managed by the application lifespan
|
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.error(f"Error disconnecting database after initial sync: {e}")
|
logger.error(f"Error disconnecting database after initial sync: {e}")
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,3 @@
|
|||||||
"""
|
|
||||||
应用程序工厂模块,负责创建和配置FastAPI应用程序实例
|
|
||||||
"""
|
|
||||||
from contextlib import asynccontextmanager
|
from contextlib import asynccontextmanager
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from fastapi.staticfiles import StaticFiles
|
from fastapi.staticfiles import StaticFiles
|
||||||
@@ -15,8 +12,8 @@ from app.service.key.key_manager import get_key_manager_instance
|
|||||||
from app.core.initialization import initialize_app
|
from app.core.initialization import initialize_app
|
||||||
from app.database.connection import connect_to_db, disconnect_from_db
|
from app.database.connection import connect_to_db, disconnect_from_db
|
||||||
from app.database.initialization import initialize_database
|
from app.database.initialization import initialize_database
|
||||||
from app.scheduler.key_checker import start_scheduler, stop_scheduler # 导入调度器函数
|
from app.scheduler.key_checker import start_scheduler, stop_scheduler
|
||||||
from app.service.update.update_service import check_for_updates # 导入更新检查服务
|
from app.service.update.update_service import check_for_updates
|
||||||
|
|
||||||
logger = get_application_logger()
|
logger = get_application_logger()
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
# app/services/chat/message_converter.py
|
|
||||||
|
|
||||||
from abc import ABC, abstractmethod
|
from abc import ABC, abstractmethod
|
||||||
import json
|
import json
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
# app/services/chat/response_handler.py
|
|
||||||
|
|
||||||
import base64
|
import base64
|
||||||
import json
|
import json
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
# app/services/chat/retry_handler.py
|
|
||||||
|
|
||||||
from functools import wraps
|
from functools import wraps
|
||||||
from typing import Callable, TypeVar
|
from typing import Callable, TypeVar
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
# app/services/chat/stream_optimizer.py
|
|
||||||
|
|
||||||
import asyncio
|
import asyncio
|
||||||
import math
|
import math
|
||||||
@@ -107,15 +106,11 @@ class StreamOptimizer:
|
|||||||
|
|
||||||
# 计算智能延迟时间
|
# 计算智能延迟时间
|
||||||
delay = self.calculate_delay(len(text))
|
delay = self.calculate_delay(len(text))
|
||||||
# if self.logger:
|
|
||||||
# self.logger.info(f"Text length: {len(text)}, delay: {delay:.4f}s")
|
|
||||||
|
|
||||||
# 根据文本长度决定输出方式
|
# 根据文本长度决定输出方式
|
||||||
if len(text) >= self.long_text_threshold:
|
if len(text) >= self.long_text_threshold:
|
||||||
# 长文本:分块输出
|
# 长文本:分块输出
|
||||||
chunks = self.split_text_into_chunks(text)
|
chunks = self.split_text_into_chunks(text)
|
||||||
# if self.logger:
|
|
||||||
# self.logger.info(f"Long text: splitting into {len(chunks)} chunks")
|
|
||||||
for chunk_text in chunks:
|
for chunk_text in chunks:
|
||||||
chunk_response = create_response_chunk(chunk_text)
|
chunk_response = create_response_chunk(chunk_text)
|
||||||
yield format_chunk(chunk_response)
|
yield format_chunk(chunk_response)
|
||||||
|
|||||||
@@ -113,8 +113,6 @@ class Logger:
|
|||||||
# 可选:记录级别变更日志,但注意避免在日志模块内部产生过多日志
|
# 可选:记录级别变更日志,但注意避免在日志模块内部产生过多日志
|
||||||
# print(f"Updated log level for logger '{logger_name}' to {log_level_str.upper()}")
|
# print(f"Updated log level for logger '{logger_name}' to {log_level_str.upper()}")
|
||||||
updated_count += 1
|
updated_count += 1
|
||||||
# if updated_count > 0:
|
|
||||||
# print(f"Updated log level for {updated_count} loggers to {log_level_str.upper()}.")
|
|
||||||
|
|
||||||
|
|
||||||
# 预定义的loggers
|
# 预定义的loggers
|
||||||
|
|||||||
+1
-8
@@ -1,18 +1,11 @@
|
|||||||
"""
|
|
||||||
应用程序入口模块
|
|
||||||
"""
|
|
||||||
|
|
||||||
import uvicorn
|
import uvicorn
|
||||||
|
|
||||||
from app.core.application import create_app
|
from app.core.application import create_app
|
||||||
from app.log.logger import get_main_logger
|
from app.log.logger import get_main_logger
|
||||||
|
|
||||||
# 创建应用程序实例
|
|
||||||
app = create_app()
|
app = create_app()
|
||||||
|
|
||||||
# 配置日志
|
|
||||||
logger = get_main_logger()
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
|
logger = get_main_logger()
|
||||||
logger.info("Starting application server...")
|
logger.info("Starting application server...")
|
||||||
uvicorn.run(app, host="0.0.0.0", port=8001)
|
uvicorn.run(app, host="0.0.0.0", port=8001)
|
||||||
|
|||||||
@@ -72,7 +72,6 @@ async def get_error_logs_api(
|
|||||||
error_search=error_search, # 数据库查询需要处理这个
|
error_search=error_search, # 数据库查询需要处理这个
|
||||||
start_date=start_date,
|
start_date=start_date,
|
||||||
end_date=end_date,
|
end_date=end_date,
|
||||||
# include_error_code=True # 如果需要显式传递
|
|
||||||
)
|
)
|
||||||
# Fetch total count with the same search parameters
|
# Fetch total count with the same search parameters
|
||||||
total_count = await get_error_logs_count(
|
total_count = await get_error_logs_count(
|
||||||
|
|||||||
@@ -2,12 +2,11 @@ from fastapi import APIRouter, Depends, HTTPException, Request
|
|||||||
from starlette import status
|
from starlette import status
|
||||||
from app.core.security import verify_auth_token
|
from app.core.security import verify_auth_token
|
||||||
from app.service.stats_service import StatsService
|
from app.service.stats_service import StatsService
|
||||||
from app.log.logger import get_stats_logger # 使用路由日志记录器
|
from app.log.logger import get_stats_logger
|
||||||
|
|
||||||
logger = get_stats_logger()
|
logger = get_stats_logger()
|
||||||
|
|
||||||
|
|
||||||
# 认证检查的辅助函数
|
|
||||||
async def verify_token(request: Request):
|
async def verify_token(request: Request):
|
||||||
auth_token = request.cookies.get("auth_token")
|
auth_token = request.cookies.get("auth_token")
|
||||||
if not auth_token or not verify_auth_token(auth_token):
|
if not auth_token or not verify_auth_token(auth_token):
|
||||||
@@ -21,7 +20,7 @@ async def verify_token(request: Request):
|
|||||||
router = APIRouter(
|
router = APIRouter(
|
||||||
prefix="/api",
|
prefix="/api",
|
||||||
tags=["stats"],
|
tags=["stats"],
|
||||||
dependencies=[Depends(verify_token)] # Assuming API routes need authentication
|
dependencies=[Depends(verify_token)]
|
||||||
)
|
)
|
||||||
|
|
||||||
stats_service = StatsService()
|
stats_service = StatsService()
|
||||||
@@ -52,8 +51,7 @@ async def get_key_usage_details(key: str):
|
|||||||
return {}
|
return {}
|
||||||
return usage_details
|
return usage_details
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
# Log the exception details here if needed
|
logger.error(f"Error fetching key usage details for key {key[:4]}...: {e}")
|
||||||
print(f"Error fetching key usage details for key {key[:4]}...: {e}")
|
|
||||||
raise HTTPException(
|
raise HTTPException(
|
||||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||||
detail=f"获取密钥使用详情时出错: {e}"
|
detail=f"获取密钥使用详情时出错: {e}"
|
||||||
|
|||||||
@@ -411,7 +411,6 @@ class OpenAIChatService:
|
|||||||
error_log_msg = f"Stream image completion failed for model {model}: {e}"
|
error_log_msg = f"Stream image completion failed for model {model}: {e}"
|
||||||
logger.error(error_log_msg)
|
logger.error(error_log_msg)
|
||||||
status_code = 500 # Default error code
|
status_code = 500 # Default error code
|
||||||
# Call add_error_log using the passed api_key
|
|
||||||
await add_error_log(
|
await add_error_log(
|
||||||
gemini_key=api_key,
|
gemini_key=api_key,
|
||||||
model_name=model,
|
model_name=model,
|
||||||
@@ -427,7 +426,6 @@ class OpenAIChatService:
|
|||||||
end_time = time.perf_counter()
|
end_time = time.perf_counter()
|
||||||
latency_ms = int((end_time - start_time) * 1000)
|
latency_ms = int((end_time - start_time) * 1000)
|
||||||
logger.info(f"Stream image completion for model {model} took {latency_ms} ms. Success: {is_success}")
|
logger.info(f"Stream image completion for model {model} took {latency_ms} ms. Success: {is_success}")
|
||||||
# Call add_request_log using the passed api_key
|
|
||||||
await add_request_log(
|
await add_request_log(
|
||||||
model_name=model,
|
model_name=model,
|
||||||
api_key=api_key,
|
api_key=api_key,
|
||||||
@@ -460,7 +458,6 @@ class OpenAIChatService:
|
|||||||
error_log_msg = f"Normal image completion failed for model {model}: {e}"
|
error_log_msg = f"Normal image completion failed for model {model}: {e}"
|
||||||
logger.error(error_log_msg)
|
logger.error(error_log_msg)
|
||||||
status_code = 500 # Default error code
|
status_code = 500 # Default error code
|
||||||
# Call add_error_log using the passed api_key
|
|
||||||
await add_error_log(
|
await add_error_log(
|
||||||
gemini_key=api_key,
|
gemini_key=api_key,
|
||||||
model_name=model,
|
model_name=model,
|
||||||
@@ -475,7 +472,6 @@ class OpenAIChatService:
|
|||||||
end_time = time.perf_counter()
|
end_time = time.perf_counter()
|
||||||
latency_ms = int((end_time - start_time) * 1000)
|
latency_ms = int((end_time - start_time) * 1000)
|
||||||
logger.info(f"Normal image completion for model {model} took {latency_ms} ms. Success: {is_success}")
|
logger.info(f"Normal image completion for model {model} took {latency_ms} ms. Success: {is_success}")
|
||||||
# Call add_request_log using the passed api_key
|
|
||||||
await add_request_log(
|
await add_request_log(
|
||||||
model_name=model,
|
model_name=model,
|
||||||
api_key=api_key,
|
api_key=api_key,
|
||||||
|
|||||||
@@ -31,7 +31,7 @@ class ConfigService:
|
|||||||
for key, value in config_data.items():
|
for key, value in config_data.items():
|
||||||
if hasattr(settings, key):
|
if hasattr(settings, key):
|
||||||
setattr(settings, key, value)
|
setattr(settings, key, value)
|
||||||
logger.info(f"Updated setting in memory: {key}")
|
logger.debug(f"Updated setting in memory: {key}")
|
||||||
|
|
||||||
# 获取现有设置
|
# 获取现有设置
|
||||||
existing_settings_raw: List[Dict[str, Any]] = await get_all_settings()
|
existing_settings_raw: List[Dict[str, Any]] = await get_all_settings()
|
||||||
|
|||||||
@@ -88,7 +88,6 @@ class ImageCreateService:
|
|||||||
aspect_ratio=self.aspect_ratio,
|
aspect_ratio=self.aspect_ratio,
|
||||||
safety_filter_level="BLOCK_LOW_AND_ABOVE",
|
safety_filter_level="BLOCK_LOW_AND_ABOVE",
|
||||||
person_generation="ALLOW_ADULT",
|
person_generation="ALLOW_ADULT",
|
||||||
# language="auto"
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user