学弟教程-Flask+Bootstrap实现体温登记系统

  • github项目地址

文章目录

  • 一、目的
  • 二、效果
  • 三、过程
    • 技术
    • 结构
    • 3.1 前端
      • 1. HTML
    • 3.2 后端

一、目的

编写一个学生体温提交平台,可提交与删除学生当日的体温数据

二、效果

学弟教程-Flask+Bootstrap实现体温登记系统_第1张图片
学弟教程-Flask+Bootstrap实现体温登记系统_第2张图片
学弟教程-Flask+Bootstrap实现体温登记系统_第3张图片
学弟教程-Flask+Bootstrap实现体温登记系统_第4张图片

三、过程

技术

  • CSS : Bootstrap
  • JS : JQuery
  • 弹窗控件 : SweetAlert2
  • WEB框架 : Flask
  • 数据库 : sqlite

结构

学弟教程-Flask+Bootstrap实现体温登记系统_第5张图片

3.1 前端

1. HTML


<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>体温登记系统title>
    <link rel="stylesheet" href="{
      { url_for('static',filename='css/bootstrap.min.css') }}">
    <link rel="stylesheet" href="{
      { url_for('static',filename='css/sweetalert.css') }}">
    <link rel="stylesheet" href="{
      { url_for('static',filename='css/bootstrap-table.min.css') }}">

    <script src="{
      { url_for('static',filename='js/jquery.min.js') }}">script>
    <script src="{
      { url_for('static',filename='js/popper.min.js') }}">script>
    <script src="{
      { url_for('static',filename='js/bootstrap.min.js') }}">script>
    <script src="{
      { url_for('static',filename='js/sweetalert-dev.js') }}">script>
    <script src="{
      { url_for('static',filename='js/bootstrap-table.min.js') }}">script>
    <script src="{
      { url_for('static',filename='js/bootstrap-table-zh-CN.min.js') }}">script>
    <script src="{
      { url_for('static',filename='js/api.js') }}">script>
    <style>
        .danger {
      
            color: red;
            font-weight: bold;
        }

        .safe {
      
            color: green;
            font-weight: bold;
        }
    style>
head>
<body>
<div style="text-align: center;">
    <h2>体温登记h2>
div>

<table class="table table-hover">
    <form id="recordForm">
        <td>
            <div class="input-group">
                <label for="id">label>
                <input type="text" class="form-control" id="id" name="id" placeholder="请输入学号">
            div>
        td>
        <td>
            <div class="input-group">
                <label for="name">label>
                <input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名">
            div>
        td>
        <td>
            <div class="input-group">
                <label for="tem">label>
                <input type="text" class="form-control" id="tem" name="tem" placeholder="请输入体温">
            div>
        td>
        <td>
            <div class="input-group">
                <label for="date">label>
                <input type="date" class="form-control" id="date" name="date" placeholder="请选择日期">
            div>
        td>
        <td>
            <button type="button" class="btn btn-primary" onclick=addRecord()>提交button>
        td>
    form>
table>
<table class="table table-hover" id="recordTable">
    <thead>
    <tr>
        <th>学号th>
        <th>姓名th>
        <th>体温th>
        <th>日期th>
        <th>操作th>
    tr>
    thead>
    <tbody>
    {% for i in record %}
        <tr>
            <td>{
    { i.id }}td>
            <td>{
    { i.name }}td>
            {% if i.temperature is number %}
                <td class={
      {
       "danger" if i.temperature > 37.5 else "safe" }}>
                    {
    { i.temperature }}
                td>
            {% else %}
                <td>--td>
            {% endif %}
            <td>{
    { i.date }}td>
            <td>
                
  1. JS
<script>
    function sendAjax(param, url, callback) {
     
    $.ajax({
     
        async: false,
        ache: false,
        type: 'POST',
        url: url,
        //JSON对象转化JSON字符串
        data: JSON.stringify(param),
        //服务器返回的数据类型
        dataType: "json",
        success: function (data) {
     
            callback(data.result)
        },
        error: function (data) {
     
            //错误处理
        }
    })
}

function addRecord() {
     
    var data = {
     
        'id': $('#id').val(),
        'name': $('#name').val(),
        'tem': $('#tem').val(),
        'date': $('#date').val()
    }
    //判断体温是否为数字
    var regPos = /^\d+(\.\d+)?$/

    if (!regPos.test(parseFloat(data['tem']))) {
     
        swal({
     
            title: "请输入正确的体温格式",
            text: "体温格式",
            type: "error"
        }, function () {
     
            $('#tem').val("")
        })
        return
    }
    if (data['tem'] < 35.0 || data['tem'] > 42.9) {
     
        swal({
     
            title: "请输入正常范围的体温",
            text: "体温范围35-42℃",
            type: "error"
        }, function () {
     
            $('#tem').val("")
        })
        return
    }
    sendAjax(data, '/add', addCallback)
}

function addCallback(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({
     
                    title: "已取消",
                    text: "您取消了删除操作!",
                    type: "warning"
                })
            }
        }
    )
}

function delCallback(value) {
     
    if (value === 1) {
     
        swal({
     
            title: "删除成功",
            text: "",
            type: "success",
            timer: 2000
        }, function () {
     
            location.reload()
        })
        return
    }
    if (value === -1) {
     
        swal("删除失败", "请重试", "error")
    }
}
</script>

3.2 后端

  • app.py
from view import *


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


  • view.py
import json

import controller
from flask import Flask, render_template, request

app = Flask(__name__)


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


@app.route('/add', methods=['POST'])
def add():
    data = json.loads(request.get_data())
    res = controller.add_record(data)
    return json.dumps({
     "result": res})


@app.route('/del', methods=['POST'])
def delete():
    data = json.loads(request.get_data())
    res = controller.del_record(data)
    return json.dumps({
     "result": res})

  • controller.py
from datetime import datetime

from models import *


def add_record(data):
    # 转换日期格式为python格式
    data['date'] = datetime.strptime(data['date'], "%Y-%m-%d").date()
    # 查询是否已经提交
    if find_value(data['id']):
        return -1
    add_value(data)
    return 1


def del_record(data):
    id = data['id']
    del_value(id)
    if (find_value(id)):
        return -1
    return 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[0] else False


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

  • 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()

你可能感兴趣的:(Python,Bootstarp,python,sqlite,js,bootstarp)