學弟教程·Flask+Bootstrap+JQuery+Sqlite實現體溫登記系統

一、實驗目的

編寫一個學生體溫提交平臺,可提交與刪除學生當日的體溫數據

二、實現效果



三、實驗過程

使用技術

  • CSS : Bootstrap
  • JS : JQuery
  • 彈窗控件 : SweetAlert2
  • WEB框架 : Flask
  • 數據庫 : sqlite

項目結構

3.1 前端

1. HTML部分

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
    <script src="https://cdn.staticfile.org/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.staticfile.org/popper.js/1.15.0/umd/popper.min.js"></script>
    <script src="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://www.huangwx.cn/css/sweetalert.css">
    <script type="text/javascript" src="https://www.huangwx.cn/js/sweetalert-dev.js"></script>
    <style>
        .danger {
            color: red;
            font-weight: bold;
        }

        .safe {
            color: green;
            font-weight: bold;
        }
    </style>X
</head>
<body>
<div style="text-align: center;">
    <h2>體溫登記</h2>
</div>
<table class="table table-hover">
    <thead>
    <tr>
        <th>學號</th>
        <th>姓名</th>
        <th>體溫</th>
        <th>日期</th>
        <th></th>
    </tr>
    </thead>
    <tbody>
    <tr>
        <!--提交信息-->
        <form id="recordForm">
            <td>
                <div class="input-group">
                    <label for="id"></label>
                    <input type="text" class="form-control" id="id" name="id">
                </div>
            </td>
            <td>
                <div class="input-group">
                    <label for="name"></label>
                    <input type="text" class="form-control" id="name" name="name">
                </div>
            </td>
            <td>
                <div class="input-group">
                    <label for="tem"></label>
                    <input type="text" class="form-control" id="tem" name="tem">
                </div>
            </td>
            <td>
                <div class="input-group">
                    <label for="date"></label>
                    <input type="date" class="form-control" id="date" name="date">
                </div>
            </td>
            <td>
                <button type="button" class="btn btn-primary" onclick=submitRecord()>提交</button>
            </td>
        </form>
    </tr>
    {% for i in record %}
        <tr>
            <td>{{ i.id }}</td>
            <td>{{ i.name }}</td>
            {% if i.temperature > 37.5 %}
                <td class="danger">{{ i.temperature }}</td>
            {% else %}
                <td class="safe">{{ i.temperature }}</td>
            {% endif %}
            <td>{{ i.date }}</td>
            <td>
                <button type="button" class="btn btn-danger" οnclick=delRecord("{{ i.id }}")>刪除</button>
            </td>
        </tr>
    {% endfor %}
    </tbody>
</table>
</body>
</html>

2. JS部分

<script>
    function sendAjax(param, url, callback) {
        $.ajax({
            async: false,
            ache: false,
            type: 'POST',
            url: url,
            data: JSON.stringify(param),
            dataType: "text",
            success: function (data) {
                var value = $.parseJSON(data).result
                callback(value)
            },
            error: function (data) {
                //錯誤處理
            }
        })
    }

    function submitRecord() {
        var data = {};
        var t = $('#recordForm').serializeArray();
        $.each(t, function () {
            data[this.name] = this.value

        })
        for (var key in data) {
            if (data[key] === "") {
                //若有空值則進行相應的操作
            }
        }
        //將體溫轉換爲浮點數
        data['tem'] = parseFloat(data['tem'])
        if (data['tem'] < 35 || data['tem'] > 42) {
            swal({
                title: "請輸入正常範圍的體溫",
                text: "體溫範圍35-42℃",
                type: "error"
            }, function () {
                $('#tem').val("")
            })
            return
        }
        sendAjax(data, '/add', submitCallback)
    }

    function submitCallback(value) {
        if (value === 1) {
            swal({
                title: "提交成功",
                text: "",
                type: "success",
                timer: 2000
            }, function () {
                location.reload()
            })
        }
        if (value === 0) {
            swal("上交失敗", "請重試", "error")
        }
        if (value === -1) {
            swal({
                title: "該學生體溫已提交",
                text: "請勿重複提交",
                type: "warning"
            }, function () {
                $('#recordForm')[0].reset()
            })
        }
    }

    //刪除記錄
    function delRecord(id) {
        swal({
                title: "您確定要刪除該記錄嗎",
                text: "刪除後將無法恢復,請謹慎操作!",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "確認",
                cancelButtonText: "取消",
                closeOnConfirm: false,
                closeOnCancel: false
            },
            function (isConfirm) {
                if (isConfirm) {
                    var data = {'id': id}
                    sendAjax(data, '/del', delCallback)
                } else {
                    swal("已取消","您取消了刪除操作!","warning")
                }
            }
        )
    }

    function delCallback(value) {
        if (value === 1) {
            swal({
                title: "刪除成功",
                text: "",
                type: "success",
                timer: 2000
            }, function () {
                location.reload()
            })
        }
        if (value === -1) {
            swal("刪除失敗", "請重試", "error")
        }
    }
</script>

3.2 後端

1. app.py

from controller import *


if __name__ == '__main__':
    app.run()

2. controller.py

from models import *

import json
from datetime import datetime
from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/', methods=['POST', 'GET'])
def hello_world():
    record = get_all_record()
    return render_template('index.html', record=record)


@app.route('/add', methods=['POST'])
def add_record():
    if request.method != 'POST':
        return json.dumps({"result": 0})
    data = json.loads(request.get_data())
    # 轉換日期格式爲python格式
    data['date'] = datetime.strptime(data['date'], "%Y-%m-%d").date()
    # 查詢是否已經提交
    if find_value(data['id']):
        return json.dumps({"result": -1})
    add_value(data)
    return json.dumps({"result": 1})


@app.route('/del', methods=['POST'])
def del_record():
    if request.method != 'POST':
        return json.dumps({"result": 0})
    data = json.loads(request.get_data())
    id = data.values()
    del_value(id)
    if (find_value(id)):
        return json.dumps({"result": -1})
    return json.dumps({"result": 1})


def add_value(data):
    id, name, tem, date = data.values()
    session.add(Record(id=id, name=name, temperature=tem, date=date))
    session.commit()
    session.close()


def del_value(id):
    session.query(Record).filter(Record.id == id).delete()
    session.commit()
    session.close()


def find_value(id):
    res = session.query(Record).filter(Record.id == id).all()
    return True if res else False


def get_all_record():
    return session.query(Record).all()

3. models.py

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, String, Float, Date
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

Base = declarative_base()


class Record(Base):
    __tablename__ = 'Record'
    id = Column(String(32), primary_key=True)
    name = Column(String(32))
    temperature = Column(Float)
    date = Column(Date)


sqlite_url = 'sqlite:///demo.db?check_same_thread=False'

# 創建引擎
engine = create_engine(sqlite_url)

# 創建表
Base.metadata.create_all(engine)

# 創建DBSession類型:
Session = sessionmaker(bind=engine)

# 創建Session類實例
session = Session()

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章