更新项目配置:添加.gitignore,清理日志和缓存文件,更新应用代码
This commit is contained in:
@@ -3,8 +3,7 @@ Flask应用工厂
|
||||
"""
|
||||
import logging
|
||||
from flask import Flask
|
||||
from .config import DEBUG, SECRET_KEY, HOST, PORT
|
||||
from .health import register_health_routes
|
||||
from .config import DEBUG, HOST, PORT
|
||||
from .routes.main import register_main_routes
|
||||
|
||||
def create_app():
|
||||
@@ -15,13 +14,11 @@ def create_app():
|
||||
|
||||
# 配置
|
||||
app.config['DEBUG'] = DEBUG
|
||||
app.config['SECRET_KEY'] = SECRET_KEY
|
||||
|
||||
# 配置日志
|
||||
configure_logging(app)
|
||||
|
||||
# 注册路由
|
||||
register_health_routes(app)
|
||||
register_main_routes(app)
|
||||
|
||||
return app
|
||||
@@ -31,9 +28,16 @@ def configure_logging(app):
|
||||
if not app.debug:
|
||||
# 在生产环境中,将日志输出到文件
|
||||
import logging
|
||||
import os
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
file_handler = RotatingFileHandler('multi_camera.log', maxBytes=10240, backupCount=10)
|
||||
# 日志目录
|
||||
log_dir = './logs'
|
||||
if not os.path.exists(log_dir):
|
||||
os.makedirs(log_dir)
|
||||
|
||||
log_file = os.path.join(log_dir, 'multi_camera.log')
|
||||
file_handler = RotatingFileHandler(log_file, maxBytes=10240, backupCount=10)
|
||||
file_handler.setFormatter(logging.Formatter(
|
||||
'%(asctime)s - %(levelname)s - %(message)s'
|
||||
))
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,23 +1,18 @@
|
||||
"""
|
||||
摄像头管理器
|
||||
处理登录、会话管理和摄像头配置
|
||||
处理摄像头配置和URL生成
|
||||
"""
|
||||
import requests
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from .config import BASE_URL, LOGIN_API, CAMERA_URL, USERNAME, PASSWORD, CAMERAS
|
||||
from .config import BASE_URL, CAMERA_URL, CAMERAS
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class CameraManager:
|
||||
def __init__(self):
|
||||
self.base_url = BASE_URL
|
||||
self.login_api = LOGIN_API
|
||||
self.camera_url = CAMERA_URL
|
||||
self.session = requests.Session()
|
||||
self.token = None
|
||||
self.last_login_time = None
|
||||
self.is_logged_in = False
|
||||
self.cameras = CAMERAS
|
||||
|
||||
# 配置请求头
|
||||
@@ -28,50 +23,6 @@ class CameraManager:
|
||||
'Content-Type': 'application/json',
|
||||
'Connection': 'keep-alive',
|
||||
})
|
||||
|
||||
# 不自动登录,按需登录
|
||||
# self.auto_login()
|
||||
|
||||
def login(self):
|
||||
"""登录系统"""
|
||||
logger.info("正在登录系统...")
|
||||
|
||||
login_data = {
|
||||
'username': USERNAME,
|
||||
'password': PASSWORD,
|
||||
'email': USERNAME,
|
||||
'user': USERNAME,
|
||||
'account': USERNAME
|
||||
}
|
||||
|
||||
try:
|
||||
response = self.session.post(
|
||||
self.login_api,
|
||||
json=login_data,
|
||||
timeout=10
|
||||
)
|
||||
|
||||
if response.status_code == 200:
|
||||
response_data = response.json()
|
||||
self.token = response_data.get('token')
|
||||
self.last_login_time = datetime.now()
|
||||
self.is_logged_in = True
|
||||
|
||||
# 更新认证头
|
||||
if self.token:
|
||||
self.session.headers.update({
|
||||
'Authorization': f'Bearer {self.token}'
|
||||
})
|
||||
|
||||
logger.info("登录成功!")
|
||||
return True
|
||||
else:
|
||||
logger.error(f"登录失败,状态码: {response.status_code}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"登录请求失败: {e}")
|
||||
return False
|
||||
|
||||
def get_camera_url(self, camera_id, camera_number='mixed'):
|
||||
"""根据摄像头ID和编号生成URL"""
|
||||
|
||||
@@ -7,15 +7,12 @@ from dotenv import load_dotenv
|
||||
# 加载环境变量
|
||||
load_dotenv()
|
||||
|
||||
# 基础URL
|
||||
BASE_URL = os.getenv("BASE_URL", "http://10.80.0.2:5045")
|
||||
LOGIN_API = f"{BASE_URL}/api/user/login"
|
||||
# 基础URL(必须设置)
|
||||
BASE_URL = os.getenv("BASE_URL")
|
||||
if BASE_URL is None:
|
||||
raise ValueError("环境变量 BASE_URL 未设置")
|
||||
CAMERA_URL = f"{BASE_URL}/adaops/blank-layout/camera-view"
|
||||
|
||||
# 认证信息
|
||||
USERNAME = os.getenv("USERNAME", "hao.wang@westwell-lab.com")
|
||||
PASSWORD = os.getenv("PASSWORD", "wh707297")
|
||||
|
||||
# 摄像头配置(可以从YAML/JSON加载,这里先硬编码)
|
||||
CAMERAS = [
|
||||
{
|
||||
@@ -62,8 +59,18 @@ CAMERAS = [
|
||||
}
|
||||
]
|
||||
|
||||
# Flask配置
|
||||
DEBUG = os.getenv("FLASK_DEBUG", "False").lower() == "true"
|
||||
SECRET_KEY = os.getenv("SECRET_KEY", "dev-secret-key")
|
||||
PORT = int(os.getenv("PORT", 5002))
|
||||
HOST = os.getenv("HOST", "0.0.0.0")
|
||||
# Flask配置(必须设置)
|
||||
DEBUG_STR = os.getenv("FLASK_DEBUG")
|
||||
if DEBUG_STR is None:
|
||||
raise ValueError("环境变量 FLASK_DEBUG 未设置")
|
||||
DEBUG = DEBUG_STR.lower() == "true"
|
||||
|
||||
|
||||
PORT_STR = os.getenv("PORT")
|
||||
if PORT_STR is None:
|
||||
raise ValueError("环境变量 PORT 未设置")
|
||||
PORT = int(PORT_STR)
|
||||
|
||||
HOST = os.getenv("HOST")
|
||||
if HOST is None:
|
||||
raise ValueError("环境变量 HOST 未设置")
|
||||
@@ -1,63 +0,0 @@
|
||||
"""
|
||||
健康检查端点
|
||||
"""
|
||||
import psutil
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from flask import jsonify
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def get_memory_usage():
|
||||
"""获取内存使用(MB)"""
|
||||
process = psutil.Process()
|
||||
memory_mb = process.memory_info().rss / 1024 / 1024
|
||||
return round(memory_mb, 2)
|
||||
|
||||
def get_cpu_usage():
|
||||
"""获取CPU使用率(%)"""
|
||||
return psutil.cpu_percent(interval=0.1)
|
||||
|
||||
def register_health_routes(app):
|
||||
"""注册健康检查路由到Flask应用"""
|
||||
|
||||
@app.route('/status')
|
||||
def status():
|
||||
"""整体状态检查"""
|
||||
return jsonify({
|
||||
'status': 'ok',
|
||||
'service': 'multi-camera-monitor',
|
||||
'timestamp': datetime.now().isoformat()
|
||||
})
|
||||
|
||||
@app.route('/memory')
|
||||
def memory():
|
||||
"""内存使用"""
|
||||
return jsonify({
|
||||
'memory_mb': get_memory_usage(),
|
||||
'unit': 'MB'
|
||||
})
|
||||
|
||||
@app.route('/cpu')
|
||||
def cpu():
|
||||
"""CPU使用"""
|
||||
return jsonify({
|
||||
'cpu_percent': get_cpu_usage(),
|
||||
'unit': '%'
|
||||
})
|
||||
|
||||
@app.route('/health')
|
||||
def health():
|
||||
"""综合健康检查(用于Docker)"""
|
||||
try:
|
||||
# 简单检查
|
||||
memory = get_memory_usage()
|
||||
cpu = get_cpu_usage()
|
||||
return jsonify({
|
||||
'status': 'healthy',
|
||||
'memory_mb': memory,
|
||||
'cpu_percent': cpu
|
||||
}), 200
|
||||
except Exception as e:
|
||||
logger.error(f"健康检查失败: {e}")
|
||||
return jsonify({'status': 'unhealthy', 'error': str(e)}), 500
|
||||
@@ -1 +0,0 @@
|
||||
# 路由包
|
||||
Binary file not shown.
Binary file not shown.
@@ -45,9 +45,4 @@ def register_main_routes(app):
|
||||
return jsonify({'success': True, 'url': url})
|
||||
except Exception as e:
|
||||
return jsonify({'success': False, 'error': str(e)}), 400
|
||||
|
||||
@app.route('/api/login', methods=['POST'])
|
||||
def login():
|
||||
"""手动登录"""
|
||||
success = camera_manager.login()
|
||||
return jsonify({'success': success})
|
||||
|
||||
Reference in New Issue
Block a user