深大数据库系统实验3——DATABASE SOFTWARE练习实验

目录

一、前言

二、我的实验小变动

三、实验工程

1、板块介绍

2、实验代码

(1)__init__.py

(2)forms.py

(3)index2.py

(4)qa.py

(5)user.py

(6)bootstrap@4.6.1.min.css (模板CSS)

(7)employees.css

(8)index1.css

(9)index2.css

(10)init.css

(11)test.css

(12)jquery.3.6.1.min.js (模板js)

(13)index1.js

(14)index2.js

(15)register.js

(16)base.html

(17)customers.html

(18)employees.html

(19)index1.html

(20)index2.html

(21)login.html

(22)logs.html

(23)products.html

(24)purchases.html

(25)register.html

(26)suppliers.html

(27)app.py

(28)config.py

(29)exts.py

(30)models.py

四、运行结果


一、前言

想必进来这篇博客的同学都能下载到该实验的实验要求文件了,废话也不多讲,下面来看看这个实验。

二、我的实验小变动

该实验要求使用 PHP 构建网页以及连接数据库,但我改用了 python 的 web 框架 flask,使用  SQLAlchemy 的 ORM 操作数据库。

我的实验环境:

win11 + python3.10 + flask + Wampserver64 (MySQL)  或  Navicat Premium 16 (MySQL) 

三、实验工程

1、板块介绍

 (当然,有些css文件是空的,下面代码自然就没有放上来)

2、实验代码

(1)__init__.py

# 方便 app.py 导入蓝图

from .qa import bp as qa_bp
from .user import bp as user_bp
from .index2 import bp as index2_bp

(2)forms.py

# 主要进行表单验证,但在本实验用处不多

import wtforms
from wtforms.validators import length,email,EqualTo
from models import EmailCaptchaModel,UserModel

class employees(wtforms.Form):
    eid=wtforms.StringField(validators=[length(min=1,max=3)])
    ename = wtforms.StringField(validators=[length(min=1, max=15)])
    city = wtforms.StringField(validators=[length(min=1, max=15)])

class LoginForm(wtforms.Form):
    email = wtforms.StringField(validators=[email()])
    password = wtforms.StringField(validators=[length(min=5, max=20)])

class RegisterForm(wtforms.Form):
    username=wtforms.StringField(validators=[length(min=3,max=20)])
    email=wtforms.StringField(validators=[email()])
    captcha = wtforms.StringField(validators=[length(min=4, max=4)])
    password = wtforms.StringField(validators=[length(min=5,max=20)])
    password_confirm = wtforms.StringField(validators=[EqualTo("password")])

    def validate_captcha(self, field): # 反正这块老师是没把我讲明白的
        captcha=field.data
        email=self.email.data
        captcha_model=EmailCaptchaModel.query.filter_by(email=email).first()
        if not captcha_model and captcha_model.captcha.lower()!=captcha.lower():
            raise wtforms.ValidationError("邮箱验证码错误!")

    def validate_email(self, field): # 验证邮箱之前有没有被注册过
        email=field.data
        user_model=UserModel.query.filter_by(email=email).first()
        if user_model:
            raise wtforms.ValidationError("邮箱已经存在")

(3)index2.py

from exts import db
from flask import Blueprint,request,render_template,redirect,url_for
from .forms import employees
from models import Employees,Customers,Suppliers,Logs,Products,Purchases

bp=Blueprint("index2",__name__,url_prefix="/index2")

@bp.route("/employees/delete",methods=['GET','POST'])
def deleteEmployee():
    eid = request.form.get('eid', None)
    if eid is None:
        employs = Employees.query.all()
        return render_template("employees.html",employs=employs)
    else:
        p = Employees.query.get(eid)
        db.session.delete(p)
        db.session.commit()
        employs=Employees.query.all()
        # print(type(employs))
        # for employ in employs:
        #     print(employ.eid)
        return render_template("employees.html",employs=employs)

@bp.route("/employees/modify",methods=['GET','POST'])
def modifyEmployees():
    eid = request.form.get('eid', None)
    ename = request.form.get('ename', None)
    city = request.form.get('city', None)
    if eid is None:
        return render_template("employees.html")
    else:
        p = Employees.query.get(eid)
        p.ename=ename
        p.city=city
        db.session.commit()
        employs = Employees.query.all()
        # print(type(employs))
        # for employ in employs:
        #     print(employ.eid)
        return render_template("employees.html", employs=employs)

@bp.route("/employees/add",methods=['GET','POST'])
def addEmployees():
    # form = employees(request.form)
    # if form.validate():
        # eid=form.eid.data
        # ename=form.ename.data
        # city=form.city.data
        # employee = Employees(eid=eid,ename=ename,city=city)
    if request.method=="POST":
        eid=request.form.get('eid',None)
        ename=request.form.get('ename',None)
        city=request.form.get('city',None)
        employee = Employees(eid=eid, ename=ename, city=city)

        db.session.add(employee)
        db.session.commit()
        employs = Employees.query.all()
        return render_template("employees.html",employs=employs)
    else:
        return render_template("employees.html")




@bp.route("/employees",methods=['GET','POST'])
def queryEmployeesAll():
    employs=Employees.query.all()
    # print(type(employs))
    # for employ in employs:
    #     print(employ.eid)
    return render_template("employees.html",employs=employs)

@bp.route("/customers",methods=['GET','POST'])
def queryCustomersAll():
    customers=Customers.query.all()
    # print(type(employs))
    # for employ in employs:
    #     print(employ.eid)
    return render_template("customers.html",customers=customers)

@bp.route("/products",methods=['GET','POST'])
def queryProductsAll():
    products=Products.query.all()
    # print(type(employs))
    # for employ in employs:
    #     print(employ.eid)
    return render_template("products.html",products=products)

@bp.route("/purchases",methods=['GET','POST'])
def queryPurchasesAll():
    purchases=Purchases.query.all()
    # print(type(employs))
    # for employ in employs:
    #     print(employ.eid)
    return render_template("purchases.html",purchases=purchases)

@bp.route("/logs",methods=['GET','POST'])
def queryLogsAll():
    logs=Logs.query.all()
    # print(type(employs))
    # for employ in employs:
    #     print(employ.eid)
    return render_template("logs.html",logs=logs)

@bp.route("/suppliers",methods=['GET','POST'])
def querySuppliersAll():
    suppliers=Suppliers.query.all()
    # print(type(employs))
    # for employ in employs:
    #     print(employ.eid)
    return render_template("suppliers.html",suppliers=suppliers)




@bp.route("/customers/delete",methods=['GET','POST'])
def deleteCustomer():
    cid = request.form.get('cid', None)
    # print(cid)
    if cid is None:
        # print("2")
        customers = Customers.query.all()
        return render_template("customers.html", customers=customers)
    else:
        p = Customers.query.get(cid)
        db.session.delete(p)
        db.session.commit()
        # print("1")
        customers=Customers.query.all()
        # print(type(employs))
        # for employ in employs:
        #     print(employ.eid)
        return render_template("customers.html",customers=customers)

@bp.route("/customers/modify",methods=['GET','POST'])
def modifyCustomers():
    cid = request.form.get('cid', None)
    cname = request.form.get('cname', None)
    city = request.form.get('city', None)
    visits_made = request.form.get('visits_made', None)
    print(visits_made)
    print(visits_made)
    last_visit_time = request.form.get('last_visit_time', None)
    if cid is None:
        customers = Customers.query.all()
        return render_template("customers.html", customers=customers)
    else:
        print("1")
        p = Customers.query.get(cid)
        p.cname=cname
        p.city=city
        p.visits_made=visits_made
        p.last_visit_time=last_visit_time
        db.session.commit()
        customers = Customers.query.all()
        return render_template("customers.html", customers=customers)

@bp.route("/customers/add",methods=['GET','POST'])
def addCustomers():
    print("1")
    # form = employees(request.form)
    # if form.validate():
        # eid=form.eid.data
        # ename=form.ename.data
        # city=form.city.data
        # employee = Employees(eid=eid,ename=ename,city=city)
    if request.method=="POST":
        print("1")
        cid=request.form.get('cid',None)
        cname=request.form.get('cname2',None)
        city=request.form.get('city2',None)
        visits_made=request.form.get('visits_made2',None)
        last_visit_time=request.form.get('last_visit_time2',None)
        customer = Customers(cid=cid, cname=cname, city=city,visits_made=visits_made,last_visit_time=last_visit_time)
        print("1")
        db.session.add(customer)
        db.session.commit()
        customers = Customers.query.all()
        return render_template("customers.html",customers=customers)
    else:
        return render_template("customers.html")




@bp.route("/suppliers/modify",methods=['GET','POST'])
def modifySuppliers():
    sid = request.form.get('sid3', None)
    print(sid)
    sname = request.form.get('sname3', None)
    print(sname)
    city = request.form.get('city3', None)
    print(city)
    telephone_no = request.form.get('telephone_no3', None)
    print(telephone_no)
    if sid is None:
        suppliers = Suppliers.query.all()
        return render_template("suppliers.html", suppliers=suppliers)
    else:
        # print("1")
        p = Suppliers.query.get(sid)
        # print(p.sid,p.sname,p.city,p.telephone_no)
        # print(p)
        p.sname=sname
        # print(p.sname)
        p.city=city
        # print(p.city)
        p.telephone_no=telephone_no
        # print(p.telephone_no)
        db.session.commit()
        suppliers = Suppliers.query.all()
        # print(suppliers)
        # for i in suppliers:
        #     print(i.sid,i.sname,i.city,i.telephone_no)
        return render_template("suppliers.html", suppliers=suppliers)

@bp.route("/suppliers/delete",methods=['GET','POST'])
def deleteSupplier():
    sid = request.form.get('sid2', None)
    # print(cid)
    if sid is None:
        # print("2")
        suppliers = Suppliers.query.all()
        return render_template("suppliers.html", suppliers=suppliers)
    else:
        p = Suppliers.query.get(sid)
        db.session.delete(p)
        db.session.commit()
        # print("1")
        suppliers=Suppliers.query.all()
        # print(type(employs))
        # for employ in employs:
        #     print(employ.eid)
        return render_template("suppliers.html",suppliers=suppliers)

@bp.route("/suppliers/add",methods=['GET','POST'])
def addSuppliers():
    print("1")
    # form = employees(request.form)
    # if form.validate():
        # eid=form.eid.data
        # ename=form.ename.data
        # city=form.city.data
        # employee = Employees(eid=eid,ename=ename,city=city)
    if request.method=="POST":
        print("1")
        sid=request.form.get('sid',None)
        sname=request.form.get('sname',None)
        city=request.form.get('city',None)
        telephone_no=request.form.get('telephone_no',None)
        supplier = Suppliers(sid=sid, sname=sname, city=city,telephone_no=telephone_no)
        print("1")
        db.session.add(supplier)
        db.session.commit()
        suppliers = Suppliers.query.all()
        return render_template("suppliers.html",suppliers=suppliers)
    else:
        return render_template("suppliers.html")




@bp.route("/products/add",methods=['GET','POST'])
def addProducts():
    print("1")
    # form = employees(request.form)
    # if form.validate():
        # eid=form.eid.data
        # ename=form.ename.data
        # city=form.city.data
        # employee = Employees(eid=eid,ename=ename,city=city)
    if request.method=="POST":
        print("1")
        pid=request.form.get('pid',None)
        pname=request.form.get('pname',None)
        qoh=request.form.get('qoh',None)
        qoh_threshold=request.form.get('qoh_threshold',None)
        original_price=request.form.get('original_price',None)
        discnt_rate=request.form.get('discnt_rate',None)
        sid=request.form.get('sid',None)

        product = Products(pid=pid, pname=pname, qoh=qoh,qoh_threshold=qoh_threshold,original_price=original_price,discnt_rate=discnt_rate,sid=sid)
        print("1")
        db.session.add(product)
        db.session.commit()
        products = Products.query.all()
        return render_template("products.html",products=products)
    else:
        return render_template("products.html")

@bp.route("/products/delete",methods=['GET','POST'])
def deleteProduct():
    pid = request.form.get('pid', None)
    # print(cid)
    if pid is None:
        # print("2")
        products = Products.query.all()
        return render_template("products.html", products=products)
    else:
        p = Products.query.get(pid)
        db.session.delete(p)
        db.session.commit()
        # print("1")
        products=Products.query.all()
        # print(type(employs))
        # for employ in employs:
        #     print(employ.eid)
        return render_template("products.html",products=products)

@bp.route("/products/modify",methods=['GET','POST'])
def modifyProducts():
    pid = request.form.get('pid', None)
    pname = request.form.get('pname', None)
    qoh = request.form.get('qoh', None)
    qoh_threshold = request.form.get('qoh_threshold', None)
    original_price = request.form.get('original_price', None)
    discnt_rate = request.form.get('discnt_rate2', None)
    sid = request.form.get('sid', None)

    if pid is None:
        products = Products.query.all()
        return render_template("products.html", products=products)
    else:
        # print("1")
        p = Products.query.get(pid)
        p.pname=pname
        p.qoh=qoh
        p.qoh_threshold=qoh_threshold
        p.original_price=original_price
        p.discnt_rate=discnt_rate
        p.sid=sid

        db.session.commit()
        products = Products.query.all()
        return render_template("products.html", products=products)




@bp.route("/purchases/add",methods=['GET','POST'])
def addPurchases():
    print("1")
    # form = employees(request.form)
    # if form.validate():
        # eid=form.eid.data
        # ename=form.ename.data
        # city=form.city.data
        # employee = Employees(eid=eid,ename=ename,city=city)
    if request.method=="POST":
        print("1")
        purid=request.form.get('purid',None)
        cid=request.form.get('cid',None)
        eid=request.form.get('eid',None)
        pid=request.form.get('pid',None)
        qty=request.form.get('qty',None)
        ptime=request.form.get('ptime',None)
        total_price=request.form.get('total_price',None)

        purchase = Purchases(purid=purid,cid=cid,eid=eid,pid=pid,qty=qty,ptime=ptime,total_price=total_price)
        print("1")
        db.session.add(purchase)
        db.session.commit()
        purchases = Purchases.query.all()
        return render_template("purchases.html",purchases=purchases)
    else:
        return render_template("purchases.html")

@bp.route("/purchases/delete",methods=['GET','POST'])
def deletePurchase():
    purid = request.form.get('purid', None)
    # print(cid)
    if purid is None:
        # print("2")
        purchases = Purchases.query.all()
        return render_template("purchases.html", purchases=purchases)
    else:
        p = Purchases.query.get(purid)
        db.session.delete(p)
        db.session.commit()
        # print("1")
        purchases=Purchases.query.all()
        # print(type(employs))
        # for employ in employs:
        #     print(employ.eid)
        return render_template("purchases.html",purchases=purchases)

@bp.route("/purchases/modify",methods=['GET','POST'])
def modifyPurchases():
    purid = request.form.get('purid', None)
    cid = request.form.get('cid', None)
    eid = request.form.get('eid', None)
    pid = request.form.get('pid', None)
    qty = request.form.get('qty', None)
    ptime = request.form.get('ptime', None)
    total_price = request.form.get('total_price', None)

    if purid is None:
        purchases = Purchases.query.all()
        return render_template("purchases.html", purchases=purchases)
    else:
        # print("1")
        p = Purchases.query.get(purid)
        p.cid=cid
        p.eid=eid
        p.pid=pid
        p.qty=qty
        p.ptime=ptime
        p.total_price=total_price

        db.session.commit()
        purchases = Purchases.query.all()
        return render_template("purchases.html", purchases=purchases)




@bp.route("/logs/add",methods=['GET','POST'])
def addLogs():
    print("1")
    # form = employees(request.form)
    # if form.validate():
        # eid=form.eid.data
        # ename=form.ename.data
        # city=form.city.data
        # employee = Employees(eid=eid,ename=ename,city=city)
    if request.method=="POST":
        print("1")
        logid=request.form.get('logid',None)
        who=request.form.get('who',None)
        time=request.form.get('time',None)
        table_name=request.form.get('table_name',None)
        operation=request.form.get('operation',None)
        key_value=request.form.get('key_value',None)

        log = Logs(logid=logid,who=who,time=time,table_name=table_name,operation=operation,key_value=key_value)
        print("1")
        db.session.add(log)
        db.session.commit()
        logs = Logs.query.all()
        return render_template("logs.html",logs=logs)
    else:
        return render_template("logs.html")

@bp.route("/logs/delete",methods=['GET','POST'])
def deleteLog():
    logid = request.form.get('logid', None)
    # print(cid)
    if logid is None:
        # print("2")
        logs = Logs.query.all()
        return render_template("logs.html", logs=logs)
    else:
        p = Logs.query.get(logid)
        db.session.delete(p)
        db.session.commit()
        # print("1")
        logs=Logs.query.all()
        # print(type(employs))
        # for employ in employs:
        #     print(employ.eid)
        return render_template("logs.html",logs=logs)

@bp.route("/logs/modify",methods=['GET','POST'])
def modifyLogs():
    logid = request.form.get('logid', None)
    who = request.form.get('who', None)
    time = request.form.get('time', None)
    table_name = request.form.get('table_name', None)
    operation = request.form.get('operation', None)
    key_value = request.form.get('key_value', None)

    if logid is None:
        logs = Logs.query.all()
        return render_template("logs.html", logs=logs)
    else:
        # print("1")
        p = Logs.query.get(logid)
        p.who=who
        p.time=time
        p.table_name=table_name
        p.operation=operation
        p.key_value=key_value
        db.session.commit()
        logs = Logs.query.all()
        return render_template("logs.html", logs=logs)

(4)qa.py

from flask import Blueprint,render_template,g,request
from models import Employees,Customers,Suppliers,Products,Purchases,Logs

bp=Blueprint("qa",__name__,url_prefix="/")

@bp.route("/")
def index():
    # print(g.user.username)
    # if hasattr(g,"user"):
    #     print(g.user.username)
    # context={
    #     "user": g.user
    # }
    # return "首页"
    return render_template("login.html")

@bp.route("/index1")
def index1():
    # print(g.user.username)
    # if hasattr(g,"user"):
    #     print(g.user.username)
    # context={
    #     "user": g.user
    # }
    # return "首页"
    return render_template("index1.html")

@bp.route("/index2")
def index2():
    # print(g.user.username)
    # if hasattr(g,"user"):
    #     print(g.user.username)
    # context={
    #     "user": g.user
    # }
    # return "首页"
    customers=Customers.query.all()
    employees=Employees.query.all()
    suppliers=Suppliers.query.all()
    # for i in suppliers:
    #     print(i.sid)
    products=Products.query.all()
    purchases=Purchases.query.all()
    logs=Logs.query.all()
    return render_template("index2.html",suppliers=suppliers,employees=employees,customers=customers,products=products,purchases=purchases,logs=logs)

(5)user.py

from flask import (
    Blueprint,
    render_template,
    request,
    redirect,
    url_for,
    jsonify,
    session,
    flash
)
from exts import mail,db
from flask_mail import Message
from models import EmailCaptchaModel,UserModel

import string
import random
from datetime import datetime
from .forms import RegisterForm,LoginForm
from werkzeug.security import generate_password_hash,check_password_hash

bp=Blueprint("user",__name__,url_prefix="/user")

@bp.route("/login",methods=['GET','POST'])
def login():
    if request.method=='GET':
        return render_template("login.html")
    else:
        # print("啥玩意儿")
        form = LoginForm(request.form)
        if form.validate():
            # print("毁灭吧")
            email=form.email.data
            password=form.password.data
            user=UserModel.query.filter_by(email=email).first()
            if user and check_password_hash(user.password,password):
                session['user_id']=user.id
                return redirect("/index1")
            else:
                flash("邮箱和密码不匹配!")
                return redirect(url_for("user.login"))
        else:
            flash("邮箱或密码格式错误!")
            return redirect(url_for("user.login"))

@bp.route("/register",methods=['GET','POST'])
def register():
    if request.method == 'GET':
        # print("1111")
        return render_template("register.html")
    else:
        # print("111")
        form = RegisterForm(request.form)
        if form.validate():
            email = form.email.data
            # captcha=form.captcha.data
            username = form.username.data
            password = form.password.data

            # md5  举例:md5("huahua")=gahugduasguoydga  无法逆向
            hash_password=generate_password_hash(password)
            user = UserModel(email=email, username=username, password=hash_password)
            db.session.add(user)
            db.session.commit()
            return redirect(url_for("user.login"))
        else:
            return redirect(url_for("user.register"))

@bp.route("/logout")
def logout():
    # 清除session中所有的数据
    session.clear()
    return redirect(url_for('user.login'))

# 验证码保存到哪里:memcached/redis/数据库中(要存储数据到数据库当中,肯定要建立ORM模型)

@bp.route("/captcha",methods=['POST'])
def get_captcha():
    # GET,POST
    # email = request.args.get("email")
    email = request.form.get("email") # 改成POST后,这个获取就要改成form了
    letters=string.ascii_letters+string.digits
    captcha="".join(random.sample(letters,4))
    if email:
        message = Message(
            subject="邮箱测试",
            recipients=[email],
            body=f"【花花问答】您的注册验证码是:{captcha}, 请不要泄露您的验证码哦!"
        )
        mail.send(message)
        captcha_model = EmailCaptchaModel.query.filter_by(email=email).first()
        if captcha_model:
            captcha_model.captcha=captcha
            captcha_model.create_time=datetime.now()
            db.session.commit()
        else:
            captcha_model = EmailCaptchaModel(email=email,captcha=captcha)
            db.session.add(captcha_model)
            db.session.commit()
        print("captcha:",captcha)
        #code: 200  是一个成功的、正常的请求
        return jsonify({"code": 200})
    else:
        # code: 400  客户端错误
        return jsonify({"code": 400,"message": "请先传递邮箱!"})

(6)bootstrap@4.6.1.min.css (模板CSS)

https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css

(7)employees.css

.employee-1 {
    margin-top: 20px;
    margin-bottom: 20px;
    font-size: 30px;
}

(8)index1.css

.question1-1 {
    /*background-color: #0c5460;*/
    font-size: 30px;
    margin-top: 40px;
}

.question1-2 {
    /*background-color: #0c5460;*/
    font-size: large;
    margin-top: 40px;
}

.question1-3 {
    /*background-color: #0c5460;*/
    font-size: 30px;
    margin-top: 40px;
}

.question1-4 {
    /*background-color: #0c5460;*/
    font-size: large;
    margin-top: 40px;
}

.getTime{
    margin-top: 40px;
}

.cal {
    /*background-color: #0c5460;*/
    font-size: large;
    margin-top: 40px;
}

.print-Time{
    margin-left: 100px;
    font-size: large;
}

.cal2 {
    /*background-color: #0c5460;*/
    font-size: large;
    margin-top: 40px;
}

(9)index2.css

.index2-1 {
    margin-top: 40px;
}

.input-group {
    margin-top: 30px;
}

.input-group-label2 {
    margin-left: 20px;
}

.input-group-label3 {
    margin-left: 20px;
}

.input-group-button{
    margin-left: 20px;
}

.employee-h1 {
    font-size: 30px;
    margin-top: 30px;
}

(10)init.css

body{
    background-color: #f3f3f3;
}

(11)test.css

body{
    background-color: greenyellow;
}

(12)jquery.3.6.1.min.js (模板js)

https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js

(13)index1.js

function bindGetTimeBtnClick(){
    $("#getTime-btn").on("click",function(event){
        var now=new Date();
        var before=new Date('2020-1-15');
        var year=now.getFullYear()
        var month=now.getMonth()+1
        var day=now.getDate()
        var hour=now.getHours()
        var m=now.getMinutes()
        var s=now.getSeconds()

        var time=now.getTime()-before.getTime()

        // alert(Math.abs(parseInt(time/(1000*60*60*24))))
        // alert("今天是"+year+"年"+month+"月"+day+"日")
        // document.write(now);
        document.getElementById("printTime").innerHTML=year+"年"+month+"月"+day+"日"+hour+"时"+m+"分"+s+"秒"

        document.getElementById("calTotalDay").innerHTML= "相差 "+Math.abs(parseInt(time/(1000*60*60*24)))+" 天"
    });
}

//等网页文档所有元素都加载完成后执行
$(function () {
    bindGetTimeBtnClick();
});

(14)index2.js

function bindindex2BtnClick(){
    $("#index2-btn").on("click",function(event){
        var $this=$(this)
        var eid = $("input[name='eid']").val();
        var ename = $("input[name='ename']").val();
        var city = $("input[name='city']").val();
        // alert(eid+"  1  "+ename+"  1  "+city)
        // if(!email){
        //     alert("请先输入邮箱!");
        //     return;
        // }
        //通过js发送请求:ajax。  全称:Async JavaScript And XML (JSON)
        // 这个是Jinja2的语法: {{ url_for }}
        // $.ajax({
        //     url: "/index2",
        //     method: "POST",
        //     data:{
        //         "eid": eid,
        //         "ename": ename,
        //         "city": city
        //     },
        //
        //     success: function (res){
        //         var code=res['code'];
        //         if(code==200){
        //             alert("发送成功!")
        //         }else{
        //             alert(res['message'])
        //         }
        //     }
        // })
    });
}

//等网页文档所有元素都加载完成后执行
$(function () {
    bindindex2BtnClick();
});

(15)register.js

function bindCaptchaBtnClick(){
    $("#captcha-btn").on("click",function(event){
        var $this=$(this)
        var email = $("input[name='email']").val();
        if(!email){
            alert("请先输入邮箱!");
            return;
        }
        //通过js发送请求:ajax。  全称:Async JavaScript And XML (JSON)
        // 这个是Jinja2的语法: {{ url_for }}
        $.ajax({
            url: "/user/captcha",
            method: "POST",
            data:{
                "email": email
            },
            success: function (res){
                var code=res['code'];
                if(code==200){
                    //取消点击事件
                    $this.off("click")
                    //开始倒计时
                    var countDown=60;
                    var timer=setInterval(function(){
                        if(countDown>0){
                            $this.text(countDown+"秒后重新发送")
                        }else{
                            $this.text("获取验证码")
                            //重新执行下这个函数,重新绑定点击事件
                            bindCaptchaBtnClick();
                            //如果不需要倒计时了,那么就要记得清除倒计时,否则会一直执行下去
                            clearInterval(timer);
                        }
                        countDown-=1;
                    },1000)
                    alert("验证码发送成功!")
                }else{
                    alert(res['message'])
                }
            }
        })
    });
}

//等网页文档所有元素都加载完成后执行
$(function () {
    bindCaptchaBtnClick();
});

(16)base.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
    <link rel="stylesheet" href="{{ url_for('static',filename='bootstrap/bootstrap@4.6.1.min.css') }}">
    <link rel="stylesheet" href="{{ url_for('static',filename='css/init.css') }}">
    {% block head %}{% endblock %}
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
    <div class="container">
        <a class="navbar-brand" href="#">花花做实验</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent"
                aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav mr-auto">
                <li class="nav-item ml-5">
                    {#  加 active 会高亮显示 #}
                    {% if user %}
                        <a class="nav-link" href="{{ url_for('qa.index1') }}">思考题一<span
                                class="sr-only">(current)</span></a>
                    {% else %}
                        <a class="nav-link" href="#">思考题一<span class="sr-only">(current)</span></a>
                    {% endif %}
                </li>
                <li class="nav-item ml-4">
                    {% if user %}
                        <a class="nav-link" href="{{ url_for('qa.index2') }}">思考题二</a>
                    {% else %}
                        <a class="nav-link" href="#">思考题二</a>
                    {% endif %}
                </li>
                {#                <li class="nav-item dropdown">#}
                {#                    <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button"#}
                {#                       data-toggle="dropdown" aria-expanded="false">#}
                {#                        Dropdown#}
                {#                    </a>#}
                {#                    <div class="dropdown-menu" aria-labelledby="navbarDropdown">#}
                {#                        <a class="dropdown-item" href="#">Action</a>#}
                {#                        <a class="dropdown-item" href="#">Another action</a>#}
                {#                        <div class="dropdown-divider"></div>#}
                {#                        <a class="dropdown-item" href="#">Something else here</a>#}
                {#                    </div>#}
                {#                </li>#}
                {#                <li class="nav-item">#}
                {#                    <a class="nav-link disabled">Disabled</a>#}
                {#                </li>#}
                {#                <li class="nav-item ml-5">#}
                {#                    <form class="form-inline my-2 my-lg-0">#}
                {#                        <input class="form-control mr-sm-2" type="search" placeholder="关键字" aria-label="Search">#}
                {#                        <button class="btn btn-outline-success my-2 my-sm-0" type="submit">搜索</button>#}
                {#                    </form>#}
                {#                </li>#}

                <select class="nav-item ml-5 mt-1" onchange="javascript:location.href=this.value;">
                    <option selected>select tables</option>
                    <option value="{{ url_for('index2.queryEmployeesAll') }}">--------employees-------</option>
                    <option value="{{ url_for('index2.queryCustomersAll') }}">--------Customers-------</option>
                    <option value="{{ url_for('index2.querySuppliersAll') }}">--------Suppliers-------</option>
                    <option value="{{ url_for('index2.queryProductsAll') }}">---------Products--------</option>
                    <option value="{{ url_for('index2.queryPurchasesAll') }}">--------Purchases--------</option>
                    <option value="{{ url_for('index2.queryLogsAll') }}">----------Logs-----------</option>
                </select>


            </ul>
            <ul class="navbar-nav">
                {% if user %}
                    <li class="nav-item">
                        <span class="nav-link">{{ user.username }}</span>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ url_for('user.logout') }}">退出登录</a>
                    </li>
                {% else %}
                    <li class="nav-item">
                        <a class="nav-link" href="{{ url_for('user.login') }}">登陆</a>
                    </li>
                    <li class="nav-item">
                        <a class="nav-link" href="{{ url_for('user.register') }}">注册</a>
                    </li>
                {% endif %}

            </ul>
        </div>
    </div>
</nav>
<div class="container">{% block body %}{% endblock %}</div>
</body>
</html>

(17)customers.html

{% extends "base.html" %}

{% block title %} 花花问答-customers {% endblock %}

{% block head %}
<link rel="stylesheet" href="{{ url_for('static',filename='css/employees.css') }}">
{% endblock %}

{% block body %}
    <div class="employee-1">customers表格</div>
    <table class="table index2-1">
        <thead>
        <tr>
            <th scope="col">cid</th>
            <th scope="col">cname</th>
            <th scope="col">city</th>
            <th scope="col">visits_made</th>
            <th scope="col">last_visit_time</th>
        </tr>
        </thead>
        <tbody>

        {% for customer in customers %}
            <tr>
                <td>{{ customer.cid }}</td>
                <td>{{ customer.cname }}</td>
                <td>{{ customer.city }}</td>
                <td>{{ customer.visits_made }}</td>
                <td>{{ customer.last_visit_time }}</td>
            </tr>
        {% endfor %}

        </tbody>
    </table>
{% endblock %}

(18)employees.html

{% extends "base.html" %}

{% block title %} 花花问答-employees {% endblock %}

{% block head %}
<link rel="stylesheet" href="{{ url_for('static',filename='css/employees.css') }}">
{% endblock %}

{% block body %}
    <div class="employee-1">employees表格</div>
    <table class="table index2-1">
        <thead>
        <tr>
            <th scope="col">eid</th>
            <th scope="col">ename</th>
            <th scope="col">city</th>
        </tr>
        </thead>
        <tbody>

        {% for employ in employs %}
            <tr>
                <td>{{ employ.eid }}</td>
                <td>{{ employ.ename }}</td>
                <td>{{ employ.city }}</td>
            </tr>
        {% endfor %}

        </tbody>
    </table>

{% endblock %}

(19)index1.html

{% extends "base.html" %}

{% block title %} 花花问答-思考题1 {% endblock %}

{% block head %}
    <link rel="stylesheet" href="{{ url_for('static',filename='css/index1.css') }}">
    <script src="{{ url_for('static',filename='jquery/jquery.3.6.1.min.js') }}"></script>
    <script src="{{ url_for('static',filename='js/index1.js') }}"></script>
{% endblock %}

{% block body %}
    <div class="question1-1">
        思考题一:
    </div>
    <div class="question1-2">
        <p>建立一个页面,打印出现在的时间,同时计算出与2020年寒假(寒假开始日期:2020/1/15)相差的天数,用适当的方式显示。</p>
    </div>
    <div class="question1-3">
        解答:{{ year }}
    </div>
    <div class="question1-4">
        (1)打印出现在的时间
    </div>
    <div class="getTime">
        <span>
            <button class="btn btn-outline-secondary" type="button" id="getTime-btn">获取当下的时间并计算相差天数</button>
        </span>
        <span class="print-Time" id="printTime" style="color: red">
            {{ printTime }}
        </span>
    </div>
    <div class="cal">
        (2)计算当下日期与2020年1月15日相差的天数
    </div>
    <div class="cal2" id="calTotalDay" style="color: red">
        {{calTotalDay}}
    </div>
{% endblock %}

(20)index2.html

{% extends "base.html" %}

{% block title %} 花花问答-思考题2 {% endblock %}

{% block head %}
    <link rel="stylesheet" href="{{ url_for('static',filename='css/index2.css') }}">
    <script src="{{ url_for('static',filename='jquery/jquery.3.6.1.min.js') }}"></script>
    <script src="{{ url_for('static',filename='js/index2.js') }}"></script>
{% endblock %}

{% block body %}
    <!employees插入数据>
    <div class="employee-h1">(1) employees操作</div>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.addEmployees') }}">
        <label class="ml-5">插入数据: eid:
            <input name="eid" autocomplete="name">
        </label>
        <label class="input-group-label2">ename:
            <input name="ename" autocomplete="name">
        </label>
        <label class="input-group-label3">city:
            <input name="city" autocomplete="name">
        </label>
        <span class="input-group-button ml-auto">
            <button type="submit" id="index2-btn">insert</button>
        </span>
    </form>

    <!employees删除数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.deleteEmployee') }}">
        <label class="ml-5">删除数据: eid:
            <input name="eid" autocomplete="name">
        </label>
        <span class="input-group-button ml-auto">
            <button type="submit" id="index2-btn">drop</button>
        </span>
    </form>

    <!employees修改数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.modifyEmployees') }}">
        <label class="ml-5">修改数据: eid:
            <input name="eid" autocomplete="name">
        </label>
        <label class="input-group-label2">ename:
            <input name="ename" autocomplete="name">
        </label>
        <label class="input-group-label3">city:
            <input name="city" autocomplete="name">
        </label>
        <span class="input-group-button ml-auto">
            <button type="submit" id="index2-btn">modify</button>
        </span>
    </form>



    <!customers插入数据>
    <div class="employee-h1">(2) customers操作</div>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.addCustomers') }}">

        <div>
            <label class="ml-5">插入数据: cid:
                <input name="cid" autocomplete="name">
            </label>
            <label class="input-group-label2">cname:
                <input name="cname2" autocomplete="name">
            </label>
            <label class="input-group-label3 ">city:
                <input name="city2" autocomplete="name">
            </label>
        </div>

        <div class="pl-5">
            <label class="input-group-label3 ml-auto">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspvisits_made:
                <input name="visits_made2" autocomplete="name">
            </label>

            <label class="input-group-label3">last_visit_time:
                <input type="datetime-local" name="last_visit_time2" autocomplete="name">
            </label>
        </div>

        <span class="input-group-button ml-auto">
            <button type="submit">insert</button>
        </span>
    </form>

    <!customers删除数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.deleteCustomer') }}">
        <label class="ml-5" for="textx">删除数据: cid:
            <input type="search" list="textxx" id="textx" name="cid" autocomplete="name"
                   placeholder="请选择"/>
            <datalist id="textxx">
                {% for customer in customers %}
                    <option value="{{ customer.cid }}"></option>
                {% endfor %}
            </datalist>
        </label>

        <span class="input-group-button ml-auto">
                <button type="submit">drop</button>
            </span>
    </form>

    <!customers修改数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.modifyCustomers') }}">

        <div>
            <label class="ml-5" for="textx">修改数据: cid:
                <input type="search" list="text2" id="textx" name="cid" autocomplete="name"
                       placeholder="请选择"/>
                <datalist id="text2">
                    {% for customer in customers %}
                        <option value="{{ customer.cid }}"></option>
                    {% endfor %}
                </datalist>
            </label>

            <label class="input-group-label2">cname:
                <input name="cname" autocomplete="name">
            </label>
            <label class="input-group-label3">city:
                <input name="city" autocomplete="name">
            </label>
        </div>

        <div class="pl-5">
            <label class="input-group-label3 ml-auto">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspvisits_made:
                <input name="visits_made" autocomplete="name">
            </label>
            <label class="input-group-label3">last_visit_time:
                <input type="datetime-local" name="last_visit_time" autocomplete="name">
            </label>
        </div>
        <span class="input-group-button ml-auto">
            <button type="submit">modify</button>
        </span>
    </form>



    <!suppliers插入数据>
    <div class="employee-h1">(3) suppliers操作</div>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.addSuppliers') }}">
        <label class="ml-5">插入数据: sid:
            <input name="sid" autocomplete="name">
        </label>
        <label class="input-group-label2">sname:
            <input name="sname" autocomplete="name">
        </label>
        <label class="input-group-label3 ">city:
            <input name="city" autocomplete="name">
        </label>
        <div class="pl-5">
            <label class="input-group-label3 ml-auto">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsptelephone_no:
                <input name="telephone_no" autocomplete="name">
            </label>
        </div>
        <span class="input-group-button ml-auto">
            <button type="submit">insert</button>
        </span>
    </form>

    <!suppliers删除数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.deleteSupplier') }}">
        <label class="ml-5" for="text-aa">删除数据: sid:
            <input type="search" list="text-xxx" id="text-aa" name="sid2" autocomplete="name"
                   placeholder="请选择"/>
            <datalist id="text-xxx">
                {% for supplier in suppliers %}
                    <option value="{{ supplier.sid }}"></option>
                {% endfor %}
            </datalist>
        </label>

        <span class="input-group-button ml-auto">
                <button type="submit">drop</button>
            </span>
    </form>

    <!suppliers修改数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.modifySuppliers') }}">

        <label class="ml-5" for="text-1">修改数据: sid:
            <input type="search" list="text-xxx" id="text-1" name="sid3" autocomplete="name"
                   placeholder="请选择"/>
            <datalist id="text-xxx">
                {% for supplier in suppliers %}
                    <option value="{{ supplier.sid }}"></option>
                {% endfor %}
            </datalist>
        </label>

        {#        <label class="ml-5">修改数据: cid:#}
        {#            <input name="cid" autocomplete="name">#}
        {#        </label>#}

        <label class="input-group-label2">sname:
            <input name="sname3" autocomplete="name">
        </label>
        <label class="input-group-label3">city:
            <input name="city3" autocomplete="name">
        </label>
        <div class="pl-5">
            <label class="input-group-label3 ml-auto">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsptelephone_no:
                <input name="telephone_no3" autocomplete="name">
            </label>
        </div>
        <span class="input-group-button ml-auto">
            <button type="submit">modify</button>
        </span>
    </form>



    <!products插入数据>
    <div class="employee-h1">(4) products操作</div>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.addProducts') }}">
        <label class="ml-5">插入数据: pid:
            <input name="pid" autocomplete="name">
        </label>
        <label class="input-group-label2">pname:
            <input name="pname" autocomplete="name">
        </label>
        <label class="input-group-label3 ">qoh:
            <input name="qoh" autocomplete="name">
        </label>

        <div class="pl-5">
            <label class="input-group-label3 ml-auto">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspqoh_threshold:
                <input name="qoh_threshold" autocomplete="name">
            </label>
            <label class="input-group-label3 ">original_price:
                <input name="original_price" autocomplete="name">
            </label>
            <label class="input-group-label3 ">discnt_rate:
                <input name="discnt_rate" autocomplete="name">
            </label>
        </div>

        <label class="input-group-label3 pl-5">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspsid:
            <input name="sid" autocomplete="name">
        </label>
        <span class="input-group-button ml-auto">
            <button type="submit">insert</button>
        </span>
    </form>

    <!products删除数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.deleteProduct') }}">
        <label class="ml-5" for="text-aaa">删除数据: pid:
            <input type="search" list="text-xxxx" id="text-aaa" name="pid" autocomplete="name"
                   placeholder="请选择"/>
            <datalist id="text-xxxx">
                {% for product in products %}
                    <option value="{{ product.pid }}"></option>
                {% endfor %}
            </datalist>
        </label>

        <span class="input-group-button ml-auto">
            <button type="submit">drop</button>
        </span>
    </form>

    <!products修改数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.modifyProducts') }}">

        <label class="ml-5" for="text-11">修改数据: pid:
            <input type="search" list="text-xxxx" id="text-11" name="pid" autocomplete="name"
                   placeholder="请选择"/>
            <datalist id="text-xxxx">
                {% for product in products %}
                    <option value="{{ product.pid }}"></option>
                {% endfor %}
            </datalist>
        </label>

        <label class="input-group-label2">pname:
            <input name="pname" autocomplete="name">
        </label>
        <label class="input-group-label3">qoh:
            <input name="qoh" autocomplete="name">
        </label>

        <div class="pl-5">
            <label class="input-group-label3 ml-auto">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspqoh_threshold:
                <input name="qoh_threshold" autocomplete="name">
            </label>
            <label class="input-group-label3">original_price:
                <input name="original_price" autocomplete="name">
            </label>
            <label class="input-group-label3">discnt_rate:
                <input name="discnt_rate2" autocomplete="name">
            </label>
        </div>

        <div class="pl-5">
            <label class="input-group-label3 ml-auto">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspsid:
                <input name="sid" autocomplete="name">
            </label>
        </div>

        <span class="input-group-button ml-auto">
            <button type="submit">modify</button>
        </span>
    </form>




    <!purchases插入数据>
    <div class="employee-h1">(5) purchases操作</div>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.addPurchases') }}">
        <label class="ml-5">插入数据: purid:
            <input name="purid" autocomplete="name">
        </label>
        <label class="input-group-label2">cid:
            <input name="cid" autocomplete="name">
        </label>
        <label class="input-group-label3 ">eid:
            <input name="eid" autocomplete="name">
        </label>
        <label class="input-group-label3 ml-auto">pid:
            <input name="pid" autocomplete="name">
        </label>

        <div class="pl-5">
            <label class="input-group-label3 ">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspqty:
                <input name="qty" autocomplete="name">
            </label>
            <label class="input-group-label3 ">ptime:
                <input type="datetime-local" name="ptime" autocomplete="name">
            </label>
            <label class="input-group-label3 ">total_price:
                <input name="total_price" autocomplete="name">
            </label>
        </div>

        <span class="input-group-button ml-auto">
            <button type="submit">insert</button>
        </span>
    </form>

    <!purchases删除数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.deletePurchase') }}">
        <label class="ml-5" for="text-aaaa">删除数据: purid:
            <input type="search" list="text-xxxxx" id="text-aaaa" name="purid" autocomplete="name"
                   placeholder="请选择"/>
            <datalist id="text-xxxxx">
                {% for purchase in purchases %}
                    <option value="{{ purchase.purid }}"></option>
                {% endfor %}
            </datalist>
        </label>

        <span class="input-group-button ml-auto">
            <button type="submit">drop</button>
        </span>
    </form>

    <!purchases修改数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.modifyPurchases') }}">

        <label class="ml-5" for="text-111">修改数据: purid:
            <input type="search" list="text-xxxxxxx" id="text-111" name="purid" autocomplete="name"
                   placeholder="请选择"/>
            <datalist id="text-xxxxxxx">
                {% for purchase in purchases %}
                    <option value="{{ purchase.purid }}"></option>
                {% endfor %}
            </datalist>
        </label>

        <label class="input-group-label2">cid:
            <input name="cid" autocomplete="name">
        </label>
        <label class="input-group-label3 ">eid:
            <input name="eid" autocomplete="name">
        </label>
        <label class="input-group-label3 ml-auto">pid:
            <input name="pid" autocomplete="name">
        </label>
        <div class="pl-5">
            <label class="input-group-label3 ">&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspqty:
                <input name="qty" autocomplete="name">
            </label>
            <label class="input-group-label3 ">ptime:
                <input type="datetime-local" name="ptime" autocomplete="name">
            </label>
            <label class="input-group-label3">total_price:
                <input name="total_price" autocomplete="name">
            </label>
        </div>

        <span class="input-group-button ml-auto">
            <button type="submit">modify</button>
        </span>
    </form>



    <!logs插入数据>
    <div class="employee-h1">(6) logs操作</div>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.addLogs') }}">
        <label class="ml-5">插入数据: logid:
            <input name="logid" autocomplete="name">
        </label>
        <label class="input-group-label2">who:
            <input name="who" autocomplete="name">
        </label>
        <label class="input-group-label3 ">time:
            <input type="datetime-local" name="time" autocomplete="name">
        </label>
        <label class="input-group-label3 ml-auto">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;table_name:
            <input name="table_name" autocomplete="name">
        </label>
        <label class="input-group-label3 ">operation:
            <input name="operation" autocomplete="name">
        </label>
        <label class="input-group-label3 ">key_value:
            <input name="key_value" autocomplete="name">
        </label>
        <span class="input-group-button ml-auto">
            <button type="submit">insert</button>
        </span>
    </form>

    <!logs删除数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.deleteLog') }}">
        <label class="ml-5" for="text-aaaaa">删除数据: logid:
            <input type="search" list="text-xxxxxx" id="text-aaaaa" name="logid" autocomplete="name"
                   placeholder="请选择"/>
            <datalist id="text-xxxxxx">
                {% for log in logs %}
                    <option value="{{ log.logid }}"></option>
                {% endfor %}
            </datalist>
        </label>

        <span class="input-group-button ml-auto">
            <button type="submit">drop</button>
        </span>
    </form>

    <!logs修改数据>
    <form class="input-group mt-5" method="POST" action="{{ url_for('index2.modifyLogs') }}">

        <label class="ml-5" for="text-1111">修改数据: logid:
            <input type="search" list="text-xxxxxxxxx" id="text-1111" name="logid" autocomplete="name"
                   placeholder="请选择"/>
            <datalist id="text-xxxxxxxxx">
                {% for log in logs %}
                    <option value="{{ log.logid }}"></option>
                {% endfor %}
            </datalist>
        </label>

        <label class="input-group-label2">who:
            <input name="who" autocomplete="name">
        </label>
        <label class="input-group-label3 ">time:
            <input type="datetime-local" name="time" autocomplete="name">
        </label>
        <label class="input-group-label3 ml-auto">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;table_name:
            <input name="table_name" autocomplete="name">
        </label>
        <label class="input-group-label3 ">operation:
            <input name="operation" autocomplete="name">
        </label>
        <label class="input-group-label3 ">key_value:
            <input name="key_value" autocomplete="name">
        </label>
        <span class="input-group-button ml-auto">
            <button type="submit">modify</button>
        </span>
    </form>




    <div class="pb-5 mb-5"></div>
{% endblock %}

(21)login.html

{% extends "base.html" %}

{% block title %} 花花问答-登陆 {% endblock %}

{% block head %}

{% endblock %}

{% block body %}
    <div class="row mt-5">
        <div class="col"></div>
        <div class="col">
            <form action="{{ url_for("user.login") }}" method="POST">
                <div class="form-group">
                    <label for="exampleInputEmail1">邮箱</label>
                    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" name="email">
                    <small id="emailHelp" class="form-text text-muted">我们不会将邮箱泄露给其他用户</small>
                </div>
                <div class="form-group">
                    <label for="exampleInputPassword1">密码</label>
                    <input type="password"  class="form-control" id="exampleInputPassword1" name="password">
                </div>
                {#     <div class="form-group form-check">#}
                {#     <input type="checkbox" class="form-check-input" id="exampleCheck1">#}
                {#<label class="form-check-label" for="exampleCheck1">Check me out</label>#}
                {#   </div>#}

                {% for message in get_flashed_messages() %}
                    <div class="form-group">
                        <div class="text-danger">{{ message }}</div>
                    </div>
                {% endfor %}

                <div class="form-group">
                    <button type="submit" class="btn btn-primary btn-block">立即登陆</button>
                </div>
            </form>
        </div>
        <div class="col"></div>
    </div>
{% endblock %}

(22)logs.html

{% extends "base.html" %}

{% block title %} 花花问答-logs {% endblock %}

{% block head %}
<link rel="stylesheet" href="{{ url_for('static',filename='css/employees.css') }}">
{% endblock %}

{% block body %}
    <div class="employee-1">logs表格</div>
    <table class="table index2-1">
        <thead>
        <tr>
            <th scope="col">logid</th>
            <th scope="col">who</th>
            <th scope="col">time</th>
            <th scope="col">table_name</th>
            <th scope="col">operation</th>
            <th scope="col">key_value</th>
        </tr>
        </thead>
        <tbody>

        {% for log in logs %}
            <tr>
                <td>{{ log.logid }}</td>
                <td>{{ log.who }}</td>
                <td>{{ log.time }}</td>
                <td>{{ log.table_name }}</td>
                <td>{{ log.operation }}</td>
                <td>{{ log.key_value }}</td>
            </tr>
        {% endfor %}

        </tbody>
    </table>
{% endblock %}

(23)products.html

{% extends "base.html" %}

{% block title %} 花花问答-products {% endblock %}

{% block head %}
<link rel="stylesheet" href="{{ url_for('static',filename='css/employees.css') }}">
{% endblock %}

{% block body %}
    <div class="employee-1">products表格</div>
    <table class="table index2-1">
        <thead>
        <tr>
            <th scope="col">pid</th>
            <th scope="col">pname</th>
            <th scope="col">qoh</th>
            <th scope="col">qoh_threshold</th>
            <th scope="col">original_price</th>
            <th scope="col">discnt_rate</th>
            <th scope="col">sid</th>
        </tr>
        </thead>
        <tbody>

        {% for product in products %}
            <tr>
                <td>{{ product.pid }}</td>
                <td>{{ product.pname }}</td>
                <td>{{ product.qoh }}</td>
                <td>{{ product.qoh_threshold }}</td>
                <td>{{ product.original_price }}</td>
                <td>{{ product.discnt_rate }}</td>
                <td>{{ product.sid }}</td>
            </tr>
        {% endfor %}

        </tbody>
    </table>
{% endblock %}

(24)purchases.html

{% extends "base.html" %}

{% block title %} 花花问答-purchases {% endblock %}

{% block head %}
<link rel="stylesheet" href="{{ url_for('static',filename='css/employees.css') }}">
{% endblock %}

{% block body %}
    <div class="employee-1">purchases表格</div>
    <table class="table index2-1">
        <thead>
        <tr>
            <th scope="col">purid</th>
            <th scope="col">cid</th>
            <th scope="col">eid</th>
            <th scope="col">pid</th>
            <th scope="col">qty</th>
            <th scope="col">ptime</th>
            <th scope="col">total_price</th>
        </tr>
        </thead>
        <tbody>

        {% for purchase in purchases %}
            <tr>
                <td>{{ purchase.purid }}</td>
                <td>{{ purchase.cid }}</td>
                <td>{{ purchase.eid }}</td>
                <td>{{ purchase.pid }}</td>
                <td>{{ purchase.qty }}</td>
                <td>{{ purchase.ptime }}</td>
                <td>{{ purchase.total_price }}</td>
            </tr>
        {% endfor %}

        </tbody>
    </table>
{% endblock %}

(25)register.html

{% extends "base.html" %}

{% block title %} 花花问答-注册 {% endblock %}

{% block head %}
    <script src="{{ url_for('static',filename='jquery/jquery.3.6.1.min.js') }}"></script>
    <script src="{{ url_for('static',filename='js/register.js') }}"></script>
{% endblock %}

{% block body %}
    <div class="row mt-5">
        <div class="col"></div>
        <div class="col">
            <form method="POST" action="{{ url_for('user.register') }}">
                <div class="form-group">
                    <label for="exampleInputEmail1">邮箱</label>
                    <input type="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp"
                           name="email">
                    <small id="emailHelp" class="form-text text-muted">我们不会将邮箱泄露给其他用户</small>
                </div>

                <div class="form-group">
                    <label for="exampleInputEmail1">验证码</label>
                    <div class="input-group">
                        <input type="text" class="form-control" name="captcha">
                        <div class="input-group-append">
                            <button class="btn btn-outline-secondary" type="button" id="captcha-btn">获取验证码</button>
                        </div>
                    </div>
                </div>

                <div class="form-group">
                    <label for="exampleInputEmail1">用户名</label>
                    <input type="text" class="form-control" name="username">
                </div>

                <div class="form-group">
                    <label for="exampleInputPassword1">密码</label>
                    <input type="password" class="form-control" id="exampleInputPassword1" name="password">
                </div>

                <div class="form-group">
                    <label for="exampleInputPassword1">确认密码</label>
                    <input type="password" class="form-control" name="password_confirm">
                </div>
                {#     <div class="form-group form-check">#}
                {#     <input type="checkbox" class="form-check-input" id="exampleCheck1">#}
                {#<label class="form-check-label" for="exampleCheck1">Check me out</label>#}
                {#   </div>#}
                <button type="submit" class="btn btn-primary btn-block">立即登陆</button>
            </form>
        </div>
        <div class="col"></div>
    </div>
{% endblock %}

(26)suppliers.html

{% extends "base.html" %}

{% block title %} 花花问答-suppliers {% endblock %}

{% block head %}
<link rel="stylesheet" href="{{ url_for('static',filename='css/employees.css') }}">
{% endblock %}

{% block body %}
    <div class="employee-1">suppliers表格</div>
    <table class="table index2-1">
        <thead>
        <tr>
            <th scope="col">sid</th>
            <th scope="col">sname</th>
            <th scope="col">city</th>
            <th scope="col">telephone_no</th>
        </tr>
        </thead>
        <tbody>

        {% for supplier in suppliers %}
            <tr>
                <td>{{ supplier.sid }}</td>
                <td>{{ supplier.sname }}</td>
                <td>{{ supplier.city }}</td>
                <td>{{ supplier.telephone_no }}</td>
            </tr>
        {% endfor %}

        </tbody>
    </table>
{% endblock %}

(27)app.py

from flask import Flask,session,g
import config
from exts import db,mail
# from blueprints.qa import bp as qa_bp
from blueprints import qa_bp
from blueprints import user_bp
from blueprints import index2_bp
from flask_migrate import Migrate
from models import UserModel

app = Flask(__name__)
app.config.from_object(config) # 这样就绑定了 config.py
db.init_app(app)
mail.init_app(app)

migrate=Migrate(app,db)

app.register_blueprint(qa_bp)
app.register_blueprint(user_bp)
app.register_blueprint(index2_bp)

@app.before_request    # 钩子函数
def before_request():
    user_id=session.get("user_id")
    if user_id:
        try:
            user=UserModel.query.get(user_id)
            # 给g绑定一个叫做user的变量,他的值是user这个变量, 全局g在项目的任何地方都可以使用
            # setattr(g,"user",user)
            g.user=user
        except:
            g.user=None

# 请求来了 -> before_request -> 视图函数 -> 视图函数返回模板 -> context_processor

@app.context_processor   # 上下文处理器
def context_processor():
    if hasattr(g,"user"):
        return {"user": g.user}
    else:
        return {}

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

(28)config.py

# encoding: utf-8

import os

# 数据库的配置变量
HOSTNAME = '127.0.0.1'
PORT = '3309'
DATABASE = 'exp3'
USERNAME = 'Leo'
PASSWORD = '(隐藏)'
DB_URI = 'mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8'.format(USERNAME,PASSWORD,HOSTNAME,PORT,DATABASE)
SQLALCHEMY_DATABASE_URI = DB_URI

SQLALCHEMY_TRACK_MODIFICATIONS = True  # 跟踪修改的设置

DEBUG=True

SECRET_KEY= "haijkshdfa"


# 邮箱配置
# 该项目用的是QQ邮箱
MAIL_SERVER = "smtp.qq.com"  #如果用qq邮箱,这是一个固定的写法
MAIL_PORT = 465
MAIL_USE_TLS = False
MAIL_USE_SSL = True
MAIL_DEBUG = True
MAIL_USERNAME = "(隐藏)"
MAIL_PASSWORD = "(隐藏)"
MAIL_DEFAULT_SENDER = "(隐藏)"
# MAIL_MAX_EMAILS =
# MAIL_SUPPRESS_SEND =
# MAIL_ASCII_ATTACHMENTS =

#(隐藏内容可自己去设置)

(29)exts.py

# 这个文件就用来存放一些可能会导致循环引用的东西

from flask_sqlalchemy import SQLAlchemy
from flask_mail import Mail

db=SQLAlchemy()
mail = Mail()

(30)models.py

from exts import db
from datetime import datetime

class EmailCaptchaModel(db.Model):
    __tablename__ = "email_captcha"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    email = db.Column(db.String(100), nullable=False, unique=True)
    captcha = db.Column(db.String(10), nullable=False)
    create_time = db.Column(db.DateTime, default=datetime.now)  # now() 和 now 有细微的差别,这里采用now


class UserModel(db.Model):
    __tablename__ = "user"
    id = db.Column(db.Integer, primary_key=True, autoincrement=True)
    username = db.Column(db.String(200), nullable=False, unique=True)
    email = db.Column(db.String(100), nullable=False, unique=True)
    password = db.Column(db.String(200), nullable=False)
    join_time = db.Column(db.DateTime, default=datetime.now)


class Employees(db.Model):
    __tablename__ = "employees"
    eid = db.Column(db.String(3), primary_key=True, nullable=False, unique=True)
    ename = db.Column(db.String(15))
    city = db.Column(db.String(15))


class Customers(db.Model):
    __tablename__ = "customers"
    cid = db.Column(db.String(4), primary_key=True, nullable=False, unique=True)
    cname = db.Column(db.String(15))
    city = db.Column(db.String(15))
    visits_made = db.Column(db.Integer)
    last_visit_time = db.Column(db.DateTime)


class Suppliers(db.Model):
    __tablename__ = "suppliers"
    sid = db.Column(db.String(2), primary_key=True, nullable=False, unique=True)
    sname = db.Column(db.String(15), nullable=False)
    city = db.Column(db.String(15))
    telephone_no = db.Column(db.String(10))


class Products(db.Model):
    __tablename__ = "products"
    pid = db.Column(db.String(4), primary_key=True, nullable=False, unique=True)
    pname = db.Column(db.String(15), nullable=False)
    qoh = db.Column(db.Integer, nullable=False)
    qoh_threshold = db.Column(db.Integer)
    original_price = db.Column(db.DECIMAL(6, 2))
    discnt_rate = db.Column(db.DECIMAL(3, 2))
    sid = db.Column(db.String(2), db.ForeignKey("suppliers.sid"))


class Purchases(db.Model):
    __tablename__ = "purchases"
    purid = db.Column(db.Integer, primary_key=True, nullable=False)
    cid = db.Column(db.String(4), db.ForeignKey("customers.cid"), nullable=False)
    eid = db.Column(db.String(3), db.ForeignKey("employees.eid"), nullable=False)
    pid = db.Column(db.String(4), db.ForeignKey("products.pid"), nullable=False)
    qty = db.Column(db.Integer)
    ptime = db.Column(db.DateTime)
    total_price = db.Column(db.DECIMAL(7, 2))


class Logs(db.Model):
    __tablename__ = "logs"
    logid = db.Column(db.Integer, nullable=False, autoincrement=True, primary_key=True)
    who = db.Column(db.String(10), nullable=False)
    time = db.Column(db.DateTime, nullable=False)
    table_name = db.Column(db.String(20), nullable=False)
    operation = db.Column(db.String(6), nullable=False)
    key_value = db.Column(db.String(4))

四、运行结果

打开Wampserver64 (MySQL),运行app.py

以上,深大数据库系统实验3——DATABASE SOFTWARE练习实验

祝好

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

吕飞雨的头发不能秃

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值