图片
假设有两个用户的信息,在表中展示(分别为姓名,年龄,手机号),如下图: 支持修改及删除,点击修改时(假设只允许修改年龄及手机号),弹出如下图: 修改完,点击“用户更新”后,返回到127.0.0.1:5000/user页面
点击第二行的“删除”后,删除相关信息
python代码部分
from flask import Flask, render_template, request, redirect
app = Flask(__name__)
@app.route("/")
def index2():
return redirect('/user')
users=[{'name': 'xiaozhang', 'age': 18, 'phone':'123456'},{'name':'xiaoli','age':20,'phone':'567890'}]
@app.route('/user')
def show_user():
return render_template('/user.html', users=users)
@app.route('/del')
def del_user():
name=request.args.get('name')
for user in users:
print(user)
print(name)
if user['name'] == name:
users.remove(user)
return redirect('/user')
else:
return "no foud"
@app.route('/update',methods=['POST','GET'])
def update_info():
if request.method == 'POST':
name = request.form.get('name')
age = request.form.get('age')
phone = request.form.get('phone')
for user in users:
if user['name'] == name:
user['age'] = age
user['phone'] = phone
return redirect('/user')
return 'no found'
else:
name=request.args.get('name')
for user in users:
if user['name'] == name:
return render_template('update.html', user=user)
if __name__ == '__main__':
app.run(debug=True)
user.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>用户信息</title>
</head>
<body>
<h1>用户信息</h1>
<span>当前用户人数是:{{ users | length }}</span>
<table border="1" cellspacing="0" width="50%">
{% for user in users %}
<tr>
<td>{{ loop.index }}</td>
<td>{{ user.name }}</td>
<td>{{ user.age }}</td>
<td>{{ user.phone }}</td>
<td><a href="javascript:;" onclick="update('{{ user.name }}')">修改</a>
<a href="javascript:;" onclick="del('{{ user.name }}')">删除</a> </td>
</tr>
{% endfor %}
<script>
function del(name){
location.href='/del?name='+name
}
function update(name){
location.href='/update?name='+name
}
</script>
</table>
</body>
</html>
update.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>更新用户</title>
</head>
<body>
<form action="/update" method="POST">
<p><input type="text" name="name" placeholder="用户名" value="{{ user.name }}" disabled</p>
<p><input type="text" name="age" placeholder="年龄" value="{{ user.age }}" </p>
<p><input type="text" name="phone" placeholder="手机号" value="{{ user.phone }}" </p>
<p><input type="submit" value="用户更新"</p>
</form>
</body>
</html>
|