feat(server): 集成静态托管Flutter Web应用,统一8090端口提供Web端与监控看板

This commit is contained in:
shen
2026-10-27 20:28:37 -07:00
parent 16fb3d6606
commit 4d9df89a59
+42 -9
View File
@@ -12,7 +12,7 @@ import os
import json import json
import sqlite3 import sqlite3
import datetime import datetime
from http.server import HTTPServer, BaseHTTPRequestHandler from http.server import HTTPServer, SimpleHTTPRequestHandler
from socketserver import ThreadingMixIn from socketserver import ThreadingMixIn
DB_FILE = os.environ.get( DB_FILE = os.environ.get(
@@ -20,6 +20,11 @@ DB_FILE = os.environ.get(
os.path.join(os.path.dirname(os.path.abspath(__file__)), 'aerotrack.db') os.path.join(os.path.dirname(os.path.abspath(__file__)), 'aerotrack.db')
) )
WEB_DIR = os.environ.get(
'AEROTRACK_WEB_DIR',
os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'build', 'web')
)
def get_db(): def get_db():
conn = sqlite3.connect(DB_FILE, check_same_thread=False) conn = sqlite3.connect(DB_FILE, check_same_thread=False)
conn.row_factory = sqlite3.Row conn.row_factory = sqlite3.Row
@@ -77,21 +82,36 @@ def init_db():
class ThreadedHTTPServer(ThreadingMixIn, HTTPServer): class ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
daemon_threads = True daemon_threads = True
class SyncHandler(BaseHTTPRequestHandler): class SyncHandler(SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=WEB_DIR if os.path.isdir(WEB_DIR) else None, **kwargs)
def log_message(self, format, *args):
try:
sys.stderr.write("%s - - [%s] %s\n" %
(self.address_string(),
self.log_date_time_string(),
format % args))
sys.stderr.flush()
except Exception:
pass
def _send_cors_headers(self): def _send_cors_headers(self):
self.send_header('Access-Control-Allow-Origin', '*') self.send_header('Access-Control-Allow-Origin', '*')
self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS') self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With') self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With')
def end_headers(self):
self._send_cors_headers()
super().end_headers()
def do_OPTIONS(self): def do_OPTIONS(self):
self.send_response(200) self.send_response(200)
self._send_cors_headers()
self.end_headers() self.end_headers()
def _send_json(self, status_code, data): def _send_json(self, status_code, data):
payload = json.dumps(data, ensure_ascii=False).encode('utf-8') payload = json.dumps(data, ensure_ascii=False).encode('utf-8')
self.send_response(status_code) self.send_response(status_code)
self._send_cors_headers()
self.send_header('Content-Type', 'application/json; charset=utf-8') self.send_header('Content-Type', 'application/json; charset=utf-8')
self.send_header('Content-Length', str(len(payload))) self.send_header('Content-Length', str(len(payload)))
self.end_headers() self.end_headers()
@@ -124,7 +144,17 @@ class SyncHandler(BaseHTTPRequestHandler):
}) })
return return
# 3. 根路径:漂亮的局域网 Web 监控面板 # 3. 监控面板
if self.path == '/dashboard' or self.path == '/dashboard/':
self._render_dashboard()
return
# 4. 静态 Web 端(Flutter Web 产物)
if os.path.isdir(WEB_DIR):
super().do_GET()
return
# 5. 若未编译 Flutter Web,则默认展示监控面板
if self.path == '/' or self.path == '/index.html': if self.path == '/' or self.path == '/index.html':
self._render_dashboard() self._render_dashboard()
return return
@@ -332,8 +362,11 @@ class SyncHandler(BaseHTTPRequestHandler):
<h1 style="margin:0;font-size:22px;">AeroTrack 局域网多设备同步服务器</h1> <h1 style="margin:0;font-size:22px;">AeroTrack 局域网多设备同步服务器</h1>
<p style="margin:4px 0 0;font-size:13px;opacity:0.85;">数据安全保存在局域网私有主机,已记录 {total_count} 条雾化流水</p> <p style="margin:4px 0 0;font-size:13px;opacity:0.85;">数据安全保存在局域网私有主机,已记录 {total_count} 条雾化流水</p>
</div> </div>
<div style="background:rgba(255,255,255,0.2);padding:8px 16px;border-radius:12px;font-size:12px;font-weight:bold;"> <div style="display:flex;gap:10px;align-items:center;">
🟢 服务运行中 <a href="/" style="background:#fff;color:#2563eb;text-decoration:none;padding:8px 16px;border-radius:12px;font-size:12px;font-weight:bold;">📱 打开舒雾记 Web 端</a>
<div style="background:rgba(255,255,255,0.2);padding:8px 16px;border-radius:12px;font-size:12px;font-weight:bold;">
🟢 服务运行中
</div>
</div> </div>
</div> </div>
@@ -365,7 +398,6 @@ class SyncHandler(BaseHTTPRequestHandler):
</html>""" </html>"""
encoded = html.encode('utf-8') encoded = html.encode('utf-8')
self.send_response(200) self.send_response(200)
self._send_cors_headers()
self.send_header('Content-Type', 'text/html; charset=utf-8') self.send_header('Content-Type', 'text/html; charset=utf-8')
self.send_header('Content-Length', str(len(encoded))) self.send_header('Content-Length', str(len(encoded)))
self.end_headers() self.end_headers()
@@ -385,7 +417,8 @@ def main():
print(f"=====================================================") print(f"=====================================================")
print(f"🚀 AeroTrack 局域网同步服务器已启动!") print(f"🚀 AeroTrack 局域网同步服务器已启动!")
print(f"📡 监听端口: {port}") print(f"📡 监听端口: {port}")
print(f"🌐 局域网访问地址: http://0.0.0.0:{port}") print(f"🌐 网页版客户端: http://0.0.0.0:{port}/")
print(f"📊 监控看板大屏: http://0.0.0.0:{port}/dashboard")
print(f"💾 数据存储路径: {DB_FILE}") print(f"💾 数据存储路径: {DB_FILE}")
print(f"=====================================================") print(f"=====================================================")
try: try: