修改适配Linux

This commit is contained in:
wzy-warehouse
2026-06-24 13:03:15 +08:00
parent cd638d9a5c
commit e5582bab5d
3 changed files with 41 additions and 28 deletions
+17 -17
View File
@@ -39,26 +39,26 @@ class AppLauncher:
check_virtualenv(self.project_root) check_virtualenv(self.project_root)
# 检查是否正在使用虚拟环境运行 # 检查是否正在使用虚拟环境运行
import platform # sys.prefix != sys.base_prefix 是 Python 检测 venv 的标准方式
import sys # 不依赖路径解析,Windows/Linux 均适用
venv_path = self.project_root / ".venv" in_venv = hasattr(sys, 'real_prefix') or (
os_name = platform.system() hasattr(sys, 'base_prefix') and sys.base_prefix != sys.prefix
)
if os_name == 'Windows':
venv_python = venv_path / "Scripts" / "python.exe" if not in_venv:
else: # Linux/Mac import platform
venv_python = venv_path / "bin" / "python3" venv_path = self.project_root / ".venv"
os_name = platform.system()
# 如果当前不是使用虚拟环境的Python,则重新启动
current_python = Path(sys.executable).resolve() if os_name == 'Windows':
venv_python_resolved = venv_python.resolve() venv_python = venv_path / "Scripts" / "python.exe"
else: # Linux/Mac
if current_python != venv_python_resolved: venv_python = venv_path / "bin" / "python3"
print("\n" + "=" * 50) print("\n" + "=" * 50)
print("检测到未使用虚拟环境,正在切换到虚拟环境...") print("检测到未使用虚拟环境,正在切换到虚拟环境...")
print("=" * 50) print("=" * 50)
# 使用虚拟环境的Python重新启动应用(不传递参数避免重复检查)
import subprocess import subprocess
cmd = [str(venv_python)] + sys.argv cmd = [str(venv_python)] + sys.argv
subprocess.run(cmd, check=True) subprocess.run(cmd, check=True)
+1 -8
View File
@@ -6,8 +6,7 @@ from contextlib import asynccontextmanager
from fastapi import FastAPI, Request from fastapi import FastAPI, Request
from app.utils.api_deps import get_rainfall_model, get_earthquake_model, is_model_loaded from app.utils.api_deps import get_rainfall_model, get_earthquake_model
from app.schemas.api_schemas import HealthResponse
from app.config.paths import get_logger from app.config.paths import get_logger
from config import settings from config import settings
@@ -64,10 +63,4 @@ def create_app() -> FastAPI:
from app.api import register_routers from app.api import register_routers
register_routers(application) register_routers(application)
@application.get("/health", response_model=HealthResponse, tags=["系统"])
async def health_check():
"""健康检查"""
status = is_model_loaded()
return HealthResponse(status="ok", **status)
return application return application
+23 -3
View File
@@ -10,7 +10,7 @@ from config import settings
class RedisHelper: class RedisHelper:
"""Redis 数据库帮助类""" """Redis 数据库帮助类"""
def __init__(self): def __init__(self):
"""初始化 Redis 连接配置""" """初始化 Redis 连接配置"""
self.redis_config = { self.redis_config = {
@@ -23,7 +23,20 @@ class RedisHelper:
'socket_timeout': 5, # 读写超时时间(秒) 'socket_timeout': 5, # 读写超时时间(秒)
} }
self._client: Optional[redis.Redis] = None self._client: Optional[redis.Redis] = None
self._logged_config = False # 避免重复打印配置
def _log_config_once(self):
"""首次连接失败时打印配置信息,便于排查"""
if not self._logged_config:
from app.utils.logger import get_logger
_logger = get_logger("redis")
_logger.warning(
f"Redis 连接配置: host={self.redis_config['host']}, "
f"port={self.redis_config['port']}, db={self.redis_config['db']}, "
f"password={'***' if self.redis_config['password'] else 'None'}"
)
self._logged_config = True
@property @property
def client(self) -> redis.Redis: def client(self) -> redis.Redis:
"""获取 Redis 客户端实例(单例模式)""" """获取 Redis 客户端实例(单例模式)"""
@@ -32,10 +45,17 @@ class RedisHelper:
self._client = redis.Redis(**self.redis_config) self._client = redis.Redis(**self.redis_config)
# 测试连接 # 测试连接
self._client.ping() self._client.ping()
except redis.AuthenticationError as e:
self._log_config_once()
raise ConnectionError(f"Redis 认证失败(密码错误): {e}")
except redis.ConnectionError as e: except redis.ConnectionError as e:
self._log_config_once()
raise ConnectionError(f"无法连接到 Redis 服务器: {e}") raise ConnectionError(f"无法连接到 Redis 服务器: {e}")
except Exception as e:
self._log_config_once()
raise ConnectionError(f"Redis 连接异常: {e}")
return self._client return self._client
def close(self): def close(self):
"""关闭 Redis 连接""" """关闭 Redis 连接"""
if self._client: if self._client: