注意:
html文件要放在templates目录下
html文件要放在templates目录下,而且该templates文件夹也应该和运行的py文件在同一级目录。
不能同时有两个在文件执行
两个在执行时,网页404了:
当关掉其它在执行的文件时,网页能够正常访问:
开机后运行前记得先启动mysql
记得要先启动mysql【重新开机后再次运行时】,否则页面可能会:
启动:(mysql57是我下载时为其设置的名字)
启动后刷新页面就能正常显示了。
1.新增用户
HTML代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>添加用户信息</title>
</head>
<body>
<h1>登记用户信息</h1>
<form method="post" action="/add/user">
<input type="text" name="user" placeholder="用户名">
<input type="text" name="pwd" placeholder="密码">
<input type="text" name="mobile" placeholder="手机号">
<input type="submit" value="提交">
</form>
</body>
</html>
python代码:
from flask import Flask,render_template,request
import pymysql
app=Flask(__name__)
@app.route("/add/user",methods=["GET","POST"])
def add_user():
if request.method=="GET":
return render_template("add_user.html")
username=request.form.get("user")
password=request.form.get("pwd")
mobile=request.form.get("mobile")
##1.连接 MySQL 2.执行 MySQL 3.关闭连接
conn=pymysql.connect(host="127.0.0.1",port=3306,user="root",passwd="root123",charset="utf8",db="unicom")
cursor=conn.cursor(pymysql.cursors.DictCursor)
sql = "insert into admin(username,password,mobile) values(%s,%s,%s)"
cursor.execute(sql, [username, password, mobile])
conn.commit()
cursor.close()
conn.close()
# print(request.form)
return "添加成功"
if __name__=='__main__':
app.run()
结果:
进入页面:
输入信息并提交:
对应表单里新增了所填信息:
2.查询所有用户(显示所有用户)
html代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>查询所有用户</title>
</head>
<body>
<table border="1">
<!--表头-->
<thead>
<tr>
<th>username</th>
<th>password</th>
<th>phonenumber</th>
</tr>
</thead>
<!--表主体-->
<tbody>
{% for item in data_list %}
<tr>
<td>{{ item.username}}</td>
<td>{{ item.password}}</td>
<td>{{ item.mobile }}</td>
</tr>
{% endfor %}
</tbody>
</table>>
</body>
</html>
python代码:
from flask import Flask,render_template,request
import pymysql
app=Flask(__name__)
@app.route("/show/user",methods=["GET","POST"])
def show_user():
# if request.method=="GET":
# return render_template("show_user.html")
##1.连接 MySQL 2.执行 MySQL 3.关闭连接
conn=pymysql.connect(host="127.0.0.1",port=3306,user="root",passwd="root123",charset="utf8",db="unicom")
cursor=conn.cursor(pymysql.cursors.DictCursor)
sql = "select * from admin"
cursor.execute(sql)
data_list=cursor.fetchall()
cursor.close()
conn.close()
print(data_list)
return render_template("show_user.html",data_list=data_list)
if __name__=='__main__':
app.run()
结果:
希望显示的表单:
成功将数据简单显示到网页上:
知识点简单提醒:
(提醒自己用的,看知识点名称回忆代码实现以及相关内容,忘了就复看上面代码,或找其它资源去复习)
input中的文本标签,form表单创建以及提交(input_submit),table表格
占位符以及其实现方式(html中,python中,以及如何连接。
……