import os import random import socket from datetime import datetime from flask import Flask, jsonify app = Flask(__name__) # 从环境变量读取版本号 VERSION = os.getenv("APP_VERSION", "v1.0") BUGGY = os.getenv("BUGGY", "false").lower() == "true" # 版本主题配置 THEMES = { "v1.0": {"color": "#4A90E2", "name": "蓝色经典版", "features": "基础功能"}, "v2.0": { "color": "#50C878", "name": "绿色升级版", "features": "新增健康检查、API接口", }, "v2.1": {"color": "#50C878", "name": "绿色稳定版", "features": "性能优化、Bug修复"}, "v3.0-buggy": { "color": "#E74C3C", "name": "红色测试版", "features": "⚠️ 此版本存在已知问题", }, } @app.route("/") def hello(): # 模拟 v3.0-buggy 的问题 if BUGGY and random.random() < 0.5: return ( f""" 服务异常
💥
服务异常:数据库连接失败
版本: {VERSION}
主机: {socket.gethostname()}
学号: s{os.getenv("STUDENT_ID", "00")}
🔄 页面每3秒自动刷新
""", 500, ) theme = THEMES.get(VERSION, THEMES["v1.0"]) return f""" Docker Swarm 滚动更新演示

🚀 {theme["name"]}

版本 {VERSION}
📦 容器主机名 {socket.gethostname()}
🎓 学号服务 s{os.getenv("STUDENT_ID", "00")}
⏰ 当前时间 {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}
✨ 版本特性 {theme["features"]}
🔄 页面每3秒自动刷新,观察容器变化
""" @app.route("/api/version") def version(): return jsonify( { "version": VERSION, "hostname": socket.gethostname(), "student_id": os.getenv("STUDENT_ID", "00"), "timestamp": datetime.now().isoformat(), "buggy": BUGGY, } ) @app.route("/health") def health(): if BUGGY and random.random() < 0.7: return {"status": "unhealthy"}, 503 return {"status": "healthy", "version": VERSION}, 200 if __name__ == "__main__": app.run(host="0.0.0.0", port=80)