运维开发第十一课课程资料

我的开源项目天眼系统的url:

GitHub – liudashang/god_eye_system: IT system topology, real-time monitoring & alerting, network Ping monitoring, latency and packet-loss visualization platform built with Flask + MySQL/MariaDB + ClickHouse + Grafana. · GitHub

Flask的文档:

Flask 欢迎您 — Flask 文档 (3.1.x) – Flask 框架

生成Form表单网页的提示词:

写一个form表单的html文件,要求网页美化格式。form表单要求通过post方法提交form-data格式的数据。
URL是“/register_user”。
form中:
一个文字输入框,标签是“姓名”,post对象名称“name”;
一个数字输入框,标签名是“年龄”,post对象名是“age”。
点击提交按钮后,网页不需要跳转,要求能够处理返回结果,返回结果为json格式,内容例子为{“error”:0,"info":"数据提交成功。"},error表示是否成功的状态,0为成功,非0为失败。info内为成功说明,或者失败的具体理由,作为给用户的结果信息展示出来。

app.py文件内容

from flask import Flask, render_template, request
import db
from datetime import datetime, timedelta
from zoneinfo import ZoneInfo
app = Flask(__name__)
db.init_app(app)

@app.after_request
def after_request(response):
    response.headers["Access-Control-Allow-Origin"] = "http://127.0.0.1:3000"
    response.headers["Access-Control-Allow-Methods"] = "GET,POST,PUT,DELETE,OPTIONS"
    response.headers["Access-Control-Allow-Headers"] = "*"
    return response

@app.route('/')
def index():
    return render_template('index.html')

@app.get("/data")
def get_data():
    connection = db.get_db()
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM alert_record")
    rows = cursor.fetchall()
    return {"data": rows}

@app.get("/add_record")
def add_record_page():
    return render_template('add_record.html')

@app.post("/add_record")
def add_record():
    alert_time = request.form['alert_time']
    level = request.form['level']
    host_name = request.form['host_name']
    alert_msg = request.form['alert_msg']
    status = request.form['status']
    recover_time = request.form['recover_time']
    print(alert_time, level, host_name, alert_msg, status, recover_time)
    alert_time = datetime.strptime(alert_time, "%Y-%m-%d %H:%M:%S") - timedelta(hours=8)
    print(alert_time)
    recover_time = datetime.strptime(recover_time, "%Y-%m-%d %H:%M:%S") - timedelta(hours=8) if recover_time else None
    print(recover_time)
    is_recover = 0
    if status == "已恢复":
        is_recover = 1
    connection = db.get_db()
    cursor = connection.cursor()
    cursor.execute("INSERT INTO alert_record (alert_time, level, host_name, alert_msg, is_recover, recover_time) VALUES (%s, %s, %s, %s, %s, %s)", (alert_time, level, host_name, alert_msg, is_recover, recover_time))
    connection.commit()
    return {"error":0,"info":"记录上传成功"}

@app.get("/del_record")
def del_record():
    id = request.args.get('id',0)
    print(id)
    if id != 0:
        connection = db.get_db()
        cursor = connection.cursor()
        cursor.execute("DELETE FROM alert_record WHERE id = %s", (id,))
        connection.commit()
        return {"error":0,"info":"记录删除成功"}
    else:
        return {"error":1,"info":"记录删除失败"}

@app.get("/update_record")
def update_record():
    id = request.args.get('id',0)
    print(id)
    connection = db.get_db()
    cursor = connection.cursor()
    cursor.execute("SELECT * FROM alert_record WHERE id = %s", (id,))
    data = cursor.fetchone()
    if data['is_recover'] == 1:
        data['status'] = "已恢复"
    else:
        data['status'] = "未恢复"
    return render_template('update_record.html', page_data=data)

@app.post("/update_record")
def update_record_post():
    id = request.args.get('id',0)

    alert_time = request.form['alert_time']
    level = request.form['level']
    host_name = request.form['host_name']
    alert_msg = request.form['alert_msg']
    status = request.form['status']
    recover_time = request.form['recover_time']
    alert_time = datetime.strptime(alert_time, "%Y-%m-%d %H:%M:%S") - timedelta(hours=8)
    recover_time = datetime.strptime(recover_time, "%Y-%m-%d %H:%M:%S") - timedelta(hours=8) if recover_time else None

    connection = db.get_db()
    cursor = connection.cursor()
    is_recover = 0
    if status == "已恢复":
        is_recover = 1
    cursor.execute("UPDATE alert_record SET alert_time = %s, level = %s, host_name = %s, alert_msg = %s, is_recover = %s, recover_time = %s WHERE id = %s", (alert_time, level, host_name, alert_msg, is_recover, recover_time, id))
    connection.commit()
    return {"error":0,"info":"记录更新成功"}

if __name__ == '__main__':
    app.run(host='127.0.0.1', port=8000, debug=True)
 

db.py文件内容

import pymysql
from pymysql.cursors import DictCursor  # 导入字典游标
from datetime import datetime
import click

from flask import current_app, g

def init_app(app):
    app.teardown_appcontext(close_db)


def get_db():
    if 'db' not in g:
        g.db = pymysql.connect(
            host = "127.0.0.1",
            port = 3306,
            user = "super",
            password = "Zhenran2026.",
            database = "grafana_demo",
            cursorclass = DictCursor  # 全局默认字典游标
        )

    return g.db


def close_db(e=None):
    db = g.pop('db', None)

    if db is not None:
        db.close()

add_record.html文件内容

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增告警记录</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-lg bg-white rounded-xl shadow-lg p-7">
        <h2 class="text-2xl font-bold text-gray-800 mb-6 text-center">新增告警记录</h2>

        <form id="alertForm">
            <!-- 告警时间 -->
            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">告警时间</label>
                <input type="datetime-local" name="alert_time" id="alert_time" required
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- 告警级别 -->
            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">告警级别</label>
                <select name="level" id="level" required
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">请选择级别</option>
                    <option value="info">info</option>
                    <option value="warning">warning</option>
                    <option value="critical">critical</option>
                </select>
            </div>

            <!-- 主机名 -->
            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">主机名</label>
                <input type="text" name="host_name" id="host_name" required placeholder="请输入主机名"
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- 告警信息 -->
            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">告警信息</label>
                <textarea name="alert_msg" id="alert_msg" rows="3" required placeholder="填写告警详情"
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"></textarea>
            </div>

            <!-- 状态 -->
            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">状态</label>
                <select name="status" id="status" required
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">请选择状态</option>
                    <option value="未恢复">未恢复</option>
                    <option value="已恢复">已恢复</option>
                </select>
            </div>

            <!-- 恢复时间 -->
            <div class="mb-5">
                <label class="block text-gray-700 font-medium mb-2">恢复时间</label>
                <input type="datetime-local" name="recover_time" id="recover_time"
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- 提交按钮 -->
            <button type="submit" id="submitBtn"
                class="w-full bg-blue-600 hover:bg-blue-700 text-white py-2.5 rounded-lg transition font-medium">
                提交
            </button>
        </form>

        <!-- 返回结果提示区域 -->
        <div id="resultBox" class="mt-5 p-4 rounded-lg hidden"></div>
    </div>

    <script>
        const form = document.getElementById('alertForm');
        const resultBox = document.getElementById('resultBox');
        const submitBtn = document.getElementById('submitBtn');

        function formatDatetimeNoTz(val) {
            if (!val) return '';
            return val.replace('T', ' ') + ':00';
        }

        form.addEventListener('submit', async function (e) {
            e.preventDefault();
            resultBox.classList.add('hidden');
            submitBtn.disabled = true;
            submitBtn.textContent = '提交中...';

            const formData = new FormData(form);
            // 覆盖时间字段
            formData.set('alert_time', formatDatetimeNoTz(document.getElementById('alert_time').value));
            formData.set('recover_time', formatDatetimeNoTz(document.getElementById('recover_time').value));

            try {
                const res = await fetch('/add_record', {
                    method: 'POST',
                    body: formData
                });
                const json = await res.json();

                if (json.error === 0) {
                    resultBox.className = 'mt-5 p-4 rounded-lg bg-green-100 text-green-700';
                } else {
                    resultBox.className = 'mt-5 p-4 rounded-lg bg-red-100 text-red-700';
                }
                resultBox.textContent = json.info;
                resultBox.classList.remove('hidden');

            } catch (err) {
                resultBox.className = 'mt-5 p-4 rounded-lg bg-red-100 text-red-700';
                resultBox.textContent = '网络请求异常:' + err.message;
                resultBox.classList.remove('hidden');
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = '提交';
            }
        })
    </script>
</body>

</html>

update_record.html文件内容

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>新增告警记录</title>
    <script src="https://cdn.tailwindcss.com"></script>
</head>

<body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
    <div class="w-full max-w-lg bg-white rounded-xl shadow-lg p-7">
        <h2 class="text-2xl font-bold text-gray-800 mb-6 text-center">新增告警记录</h2>

        <form id="alertForm">
            <!-- 告警时间 -->
            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">告警时间</label>
                <input type="datetime-local" name="alert_time" id="alert_time" required value="{{page_data['alert_time']}}"
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- 告警级别 ✅ 修复:用模板判断给option加selected -->
            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">告警级别</label>
                <select name="level" id="level" required
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">请选择级别</option>
                    <option value="info" {{ 'selected' if page_data['level'] == 'info' else '' }}>info</option>
                    <option value="warning" {{ 'selected' if page_data['level'] == 'warning' else '' }}>warning</option>
                    <option value="critical" {{ 'selected' if page_data['level'] == 'critical' else '' }}>critical</option>
                </select>
            </div>

            <!-- 主机名 -->
            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">主机名</label>
                <input type="text" name="host_name" id="host_name" required placeholder="请输入主机名" value="{{page_data['host_name']}}"
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- 告警信息 ✅ 修复:textarea的值写在标签内部,不要写value属性 -->
            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">告警信息</label>
                <textarea name="alert_msg" id="alert_msg" rows="3" required placeholder="填写告警详情"
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">{{page_data['alert_msg']}}</textarea>
            </div>

            <!-- 状态 ✅ 修复:同样option加selected判断 -->
            <div class="mb-4">
                <label class="block text-gray-700 font-medium mb-2">状态</label>
                <select name="status" id="status" required
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
                    <option value="">请选择状态</option>
                    <option value="未恢复" {{ 'selected' if page_data['status'] == '未恢复' else '' }}>未恢复</option>
                    <option value="已恢复" {{ 'selected' if page_data['status'] == '已恢复' else '' }}>已恢复</option>
                </select>
            </div>

            <!-- 恢复时间 -->
            <div class="mb-5">
                <label class="block text-gray-700 font-medium mb-2">恢复时间</label>
                <input type="datetime-local" name="recover_time" id="recover_time" value="{{page_data['recover_time']}}"
                    class="w-full px-4 py-2.5 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500">
            </div>

            <!-- 提交按钮 -->
            <button type="submit" id="submitBtn"
                class="w-full bg-blue-600 hover:bg-blue-700 text-white py-2.5 rounded-lg transition font-medium">
                提交
            </button>
        </form>

        <!-- 返回结果提示区域 -->
        <div id="resultBox" class="mt-5 p-4 rounded-lg hidden"></div>
    </div>

    <script>
        const form = document.getElementById('alertForm');
        const resultBox = document.getElementById('resultBox');
        const submitBtn = document.getElementById('submitBtn');

        function formatDatetimeNoTz(val) {
            if (!val) return '';
            return val.replace('T', ' ') + ':00';
        }

        form.addEventListener('submit', async function (e) {
            e.preventDefault();
            resultBox.classList.add('hidden');
            submitBtn.disabled = true;
            submitBtn.textContent = '提交中...';

            const formData = new FormData(form);
            // 覆盖时间字段
            formData.set('alert_time', formatDatetimeNoTz(document.getElementById('alert_time').value));
            formData.set('recover_time', formatDatetimeNoTz(document.getElementById('recover_time').value));

            try {
                const res = await fetch('/update_record?id={{page_data["id"]}}', {
                    method: 'POST',
                    body: formData
                });
                const json = await res.json();

                if (json.error === 0) {
                    resultBox.className = 'mt-5 p-4 rounded-lg bg-green-100 text-green-700';
                } else {
                    resultBox.className = 'mt-5 p-4 rounded-lg bg-red-100 text-red-700';
                }
                resultBox.textContent = json.info;
                resultBox.classList.remove('hidden');

            } catch (err) {
                resultBox.className = 'mt-5 p-4 rounded-lg bg-red-100 text-red-700';
                resultBox.textContent = '网络请求异常:' + err.message;
                resultBox.classList.remove('hidden');
            } finally {
                submitBtn.disabled = false;
                submitBtn.textContent = '提交';
            }
        })
    </script>
</body>

</html>