Files
whoami-for-swarm/app.py
seahi 8a76103cce
All checks were successful
continuous-integration/drone/push Build is passing
refactor: 优化代码结构与界面文字描述
- 规范化导入语句顺序,提升代码整洁度
- 统一使用双引号并优化代码缩进格式,提升代码风格一致性
- 更新 HTML 模板中的文字标签,将“容器主机名”改为“容器ID”并简化“学号”描述
- 优化了路由函数的代码排列和 JSON 数据的返回格式
2025-12-29 09:55:24 +08:00

57 lines
1.5 KiB
Python

import os
import socket
from datetime import datetime
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def hello():
return f"""
<!DOCTYPE html>
<html>
<head>
<title>Docker Swarm Demo</title>
<meta charset="utf-8">
<style>
body {{ font-family: Arial; max-width: 600px; margin: 50px auto; padding: 20px; }}
.info {{ background: #f0f0f0; padding: 15px; border-radius: 5px; }}
.highlight {{ color: #0066cc; font-weight: bold; }}
</style>
</head>
<body>
<h1>🐳 Docker Swarm 服务演示</h1>
<div class="info">
<p>📦 容器ID: <span class="highlight">{socket.gethostname()}</span></p>
<p>🎓 学号: <span class="highlight">s{os.getenv("STUDENT_ID", "00")}</span></p>
<p>🕒 访问时间: <span class="highlight">{datetime.now().strftime("%H:%M:%S")}</span></p>
</div>
<p style="margin-top: 20px; color: #666;">
💡 提示:多次刷新页面,观察容器主机名的变化
</p>
</body>
</html>
"""
@app.route("/api")
def api():
return jsonify(
{
"hostname": socket.gethostname(),
"student_id": os.getenv("STUDENT_ID", "00"),
"timestamp": datetime.now().isoformat(),
}
)
@app.route("/health")
def health():
return {"status": "healthy"}, 200
if __name__ == "__main__":
app.run(host="0.0.0.0", port=80)