import pymysql
import time
from flask import Flask,render_template,request
app = Flask(__name__)
#留言板列表
@app.route("/")
def index():
data=model('select * from lyb')
#return 'hello world!'
return render_template('index.html',data=data)
@app.route("/delete")
def delete():
id=request.args.get('id')
print(id)
sql=f'delete from lyb where id={id}'
res = model(sql)
if res:
return '<script>alert("删除成功!");location.href="/"</script>'
else:
return '<script>alert("删除失败!");location.href="/"</script>'
@app.route('/add')
def add():
return render_template('add.html')
@app.route('/insert',methods=['POST'])
def insert():
#1.接收表单数据
data=request.form.to_dict()
data['date'] = time.strftime('%Y-%m-%d %H:%M:%S')
print(data)
#2.把数据添加到数据库
sql=f'insert into lyb values(null,"{data["nikename"]}","{data["info"]}","{data["date"]}")'
res=model(sql)
print(res)
#3.成功添加数据,关闭数据库,返回首页
if res:
return '<script>alert("留言成功!");location.href="/"</script>'
else:
return '<script>alert("留言发布失败!");location.href="/add/"</script>'
def model(sql):
# 1.链接mysql数据库
db = pymysql.connect(host='localhost', user='root', password='123456', db='tlxy', charset='utf8mb4',
cursorclass=pymysql.cursors.DictCursor)
try:
# 2.创建游标对象
cursor = db.cursor()
# 3.准备sql
# sql = 'insert into student(name,age)values("cjw",26)'
# 4.用游标对象执行sql
row = cursor.execute(sql)
db.commit() # 在执行sql语句时,注意进行提交
# 5.提取结果.fetchall()提取所有结果。fetchone()
# data = cursor.fetchall()
# data=cursor.fetchone()
# print(row)
data=cursor.fetchall()
if data:
return data
else:
return row
except:
db.rollback() # 当代码出现错误时,进行回滚
finally:
# 6.关闭数据库链接
db.close()
@app.route("/love")
def love():
return "I love you!"
if __name__ == '__main__':
app.run(debug=False,host='127.0.0.1',port='8080')
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>留言板列表</title>
</head>
<body>
<center>
<h1 style="color: darkred">留言列表</h1>
<h3><a href="/add">添加留言</a></h3>
<table border="1" width="800">
<tr>
<th>ID编号</th>
<th>昵称</th>
<th>留言内容</th>
<th>留言时间</th>
<th>操作</th>
</tr>
{% for i in data %}
<tr>
<td>{{i.id}}</td>
<td>{{i.nikename}}</td>
<td>{{i.info}}</td>
<td>{{i.date}}</td>
<td><a href="/delete?id={{i.id}}">删除</a></td>
</tr>
{% endfor %}
</table>
</center>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加留言</title>
</head>
<body>
<center>
<h1 style="color: darkred">添加留言</h1>
<table>
<form action="/insert" method="post">
<tr>
<td>昵称:</td>
<td><input type="text" name="nikename"></td>
</tr>
<tr>
<td>留言信息:</td>
<td><textarea name="info" id="" cols="30" rows="10"></textarea></td>
</tr>
<tr>
<td><button id="add">添加</button></td>
</tr>
</form>
</table>
</center>
</body>
</html>