flask

Flask

小案例

后端

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
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")

# 保存到mysql
conn = get_conn()
insert(conn, request)
conn.close()

return "添加成功"


@app.route("/show/user")
def show_user():
conn = get_conn()
all_info = get_all(conn)
conn.close()
print(all_info)

return render_template("show_user.html", data_list=all_info)

# 获取游标
def get_conn():
conn = pymysql.connect(host="127.0.0.1",
port=3306,
user='root',
password='123456',
charset='utf8',
db='pyconn')

return conn


# 插入数据
def insert(conn, request):
info = {
"user": request.form.get("user"),
"pwd": request.form.get("pwd"),
"mobile": request.form.get("mobile"),
}
cursor = conn.cursor()
sql = "insert into admin(username, password, mobile) values (%s, %s, %s)"
cursor.execute(sql, [info["user"], info["pwd"], info["mobile"]])
conn.commit()


# 获取所有数据
def get_all(conn):
cursor = conn.cursor(pymysql.cursors.DictCursor)
sql = "select * from admin"
cursor.execute(sql)
return cursor.fetchall()


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

前端

添加用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>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>

展示用户

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户列表</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>姓名</th>
<th>密码</th>
<th>手机号</th>
</tr>
</thead>
<tbody>
{% for item in data_list %}
<tr>
<td>{{ item.id }}</td>
<td>{{ item.username }}</td>
<td>{{ item.PASSWORD }}</td>
<td>{{ item.mobile }}</td>
</tr>
{% endfor %}
</tbody>
</table>

</body>
</html>

flask
http://xwww12.github.io/2022/12/01/其他/python/flask/
作者
xw
发布于
2022年12月1日
许可协议