重构:模块化项目结构,分离配置、路由、摄像头管理器,添加健康检查,更新Dockerfile和启动脚本

This commit is contained in:
Hao Wang
2025-12-07 02:07:14 +08:00
parent e991e0e7e6
commit c4735c0d3f
21 changed files with 761 additions and 5 deletions

43
app/__init__.py Normal file
View File

@@ -0,0 +1,43 @@
"""
Flask应用工厂
"""
import logging
from flask import Flask
from .config import DEBUG, SECRET_KEY, HOST, PORT
from .health import register_health_routes
from .routes.main import register_main_routes
def create_app():
"""创建Flask应用实例"""
app = Flask(__name__,
static_folder='../static',
template_folder='templates')
# 配置
app.config['DEBUG'] = DEBUG
app.config['SECRET_KEY'] = SECRET_KEY
# 配置日志
configure_logging(app)
# 注册路由
register_health_routes(app)
register_main_routes(app)
return app
def configure_logging(app):
"""配置日志"""
if not app.debug:
# 在生产环境中,将日志输出到文件
import logging
from logging.handlers import RotatingFileHandler
file_handler = RotatingFileHandler('multi_camera.log', maxBytes=10240, backupCount=10)
file_handler.setFormatter(logging.Formatter(
'%(asctime)s - %(levelname)s - %(message)s'
))
file_handler.setLevel(logging.INFO)
app.logger.addHandler(file_handler)
app.logger.setLevel(logging.INFO)
app.logger.info('多摄像头监控系统启动')

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

103
app/camera_manager.py Normal file
View File

@@ -0,0 +1,103 @@
"""
摄像头管理器
处理登录、会话管理和摄像头配置
"""
import requests
import logging
from datetime import datetime
from .config import BASE_URL, LOGIN_API, CAMERA_URL, USERNAME, PASSWORD, 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
# 配置请求头
self.session.headers.update({
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'application/json, text/plain, */*',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'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"""
camera = next((c for c in self.cameras if c['id'] == camera_id), None)
if not camera:
raise ValueError(f"摄像头ID {camera_id} 不存在")
room = camera['room']
if camera_number == 'mixed':
return f"{self.camera_url}?room={room}&camera=mixed"
else:
return f"{self.camera_url}?room={room}&camera=camera-{camera_number}"
def refresh_camera(self, camera_id):
"""刷新指定摄像头(模拟操作)"""
logger.info(f"刷新摄像头 {camera_id}")
return True
def get_all_cameras(self):
"""返回所有摄像头配置"""
return self.cameras
def check_connection(self):
"""检查连接状态"""
try:
response = self.session.get(self.base_url, timeout=5)
return response.status_code == 200
except:
return False

69
app/config.py Normal file
View File

@@ -0,0 +1,69 @@
"""
配置文件
"""
import os
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"
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 = [
{
'id': 1,
'room': 'cnfzhjyg-igv-251',
'camera': 'mixed',
'name': '1号车',
'url': f"{CAMERA_URL}?room=cnfzhjyg-igv-251&camera=mixed"
},
{
'id': 2,
'room': 'cnfzhjyg-igv-2',
'camera': 'mixed',
'name': '2号车',
'url': f"{CAMERA_URL}?room=cnfzhjyg-igv-2&camera=mixed"
},
{
'id': 3,
'room': 'cnfzhjyg-igv-3',
'camera': 'mixed',
'name': '3号车',
'url': f"{CAMERA_URL}?room=cnfzhjyg-igv-3&camera=mixed"
},
{
'id': 4,
'room': 'cnfzhjyg-igv-5',
'camera': 'mixed',
'name': '5号车',
'url': f"{CAMERA_URL}?room=cnfzhjyg-igv-5&camera=mixed"
},
{
'id': 5,
'room': 'cnfzhjyg-igv-6',
'camera': 'mixed',
'name': '6号车',
'url': f"{CAMERA_URL}?room=cnfzhjyg-igv-6&camera=mixed"
},
{
'id': 6,
'room': 'cnfzhjyg-igv-7',
'camera': 'mixed',
'name': '7号车',
'url': f"{CAMERA_URL}?room=cnfzhjyg-igv-7&camera=mixed"
}
]
# 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")

63
app/health.py Normal file
View File

@@ -0,0 +1,63 @@
"""
健康检查端点
"""
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
app/routes/__init__.py Normal file
View File

@@ -0,0 +1 @@
# 路由包

Binary file not shown.

Binary file not shown.

53
app/routes/main.py Normal file
View File

@@ -0,0 +1,53 @@
"""
主路由
"""
import logging
from datetime import datetime
from flask import render_template, jsonify, request
from app.camera_manager import CameraManager
logger = logging.getLogger(__name__)
# 创建摄像头管理器实例(全局)
camera_manager = CameraManager()
def register_main_routes(app):
"""注册主路由到Flask应用"""
@app.route('/')
def index():
"""主页面 - 显示6个摄像头的网格布局"""
cameras = camera_manager.get_all_cameras()
return render_template('index.html',
cameras=cameras,
current_time=datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
@app.route('/api/cameras')
def get_cameras():
"""获取摄像头列表API"""
cameras = camera_manager.get_all_cameras()
return jsonify(cameras)
@app.route('/api/refresh/<int:camera_id>', methods=['POST'])
def refresh_camera(camera_id):
"""刷新指定摄像头"""
success = camera_manager.refresh_camera(camera_id)
return jsonify({'success': success, 'camera_id': camera_id})
@app.route('/api/switch', methods=['POST'])
def switch_camera():
"""切换摄像头编号"""
data = request.get_json()
camera_id = data.get('camera_id')
camera_number = data.get('camera_number', 'mixed')
try:
url = camera_manager.get_camera_url(camera_id, camera_number)
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})

53
app/templates/index.html Normal file
View File

@@ -0,0 +1,53 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>多摄像头实时监控 - AdaOps</title>
<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>
<div class="controls">
<button class="btn btn-refresh" onclick="refreshAllCameras()">🔄 刷新所有</button>
<div class="status-info">
<span class="status-item">时间: <span id="currentTime">{{ current_time }}</span></span>
</div>
</div>
<div class="camera-grid" id="cameraGrid">
{% for camera in cameras %}
<div class="camera-item" id="camera-{{ camera.id }}">
<div class="camera-header">
<div class="camera-title">{{ camera.name }}</div>
<div class="camera-status" id="status-{{ camera.id }}">✅ 在线</div>
</div>
<div class="camera-frame-container">
<iframe
class="camera-frame"
src="{{ camera.url }}"
allow="autoplay; fullscreen"
allowfullscreen
id="frame-{{ camera.id }}"
loading="lazy">
</iframe>
</div>
<div class="camera-controls-combined" id="controls-{{ camera.id }}">
<button class="cam-btn" onclick="refreshCamera({{ camera.id }})">刷新</button>
<button class="cam-btn cam-btn-fullscreen" onclick="toggleFullscreen({{ camera.id }})">全屏</button>
<button class="selector-btn active" onclick="switchCameraNumber({{ camera.id }}, 'mixed')">混合</button>
<button class="selector-btn" onclick="switchCameraNumber({{ camera.id }}, 0)">0</button>
<button class="selector-btn" onclick="switchCameraNumber({{ camera.id }}, 1)">1</button>
<button class="selector-btn" onclick="switchCameraNumber({{ camera.id }}, 2)">2</button>
<button class="selector-btn" onclick="switchCameraNumber({{ camera.id }}, 3)">3</button>
<button class="selector-btn" onclick="switchCameraNumber({{ camera.id }}, 4)">4</button>
<button class="selector-btn" onclick="switchCameraNumber({{ camera.id }}, 5)">5</button>
<button class="selector-btn" onclick="switchCameraNumber({{ camera.id }}, 6)">6</button>
<button class="selector-btn" onclick="switchCameraNumber({{ camera.id }}, 7)">7</button>
</div>
</div>
{% endfor %}
</div>
<script src="{{ url_for('static', filename='js/app.js') }}"></script>
</body>
</html>