一、代码
1. login.py
from flask import Flask, render_template, request, redirect, session, url_for
app = Flask(__name__)
app.secret_key = 'mr.hu'
app.config['DEBUG'] = True
USERS = {
1: {'name': "张桂", 'age': 17, 'gender': '男', 'text': '你过得好不好别人未必知道,但你一'},
2: {'name': '朱晨', 'age': 29, 'gender': '男', 'text': '平时骂你就算了,非要等我打你才知'},
3: {'name': '付息', 'age': 30, 'gender': '女', 'text': '人们都说陪伴是最长情的告白,其实'}
}
@app.route('/index', methods=['GET'])
def index():
# 判断是否登录了
user = session.get('user_info')
if not user:
# 反向生成url
url = url_for('login')
return redirect(url)
return render_template('index.html', user_dict=USERS)
@app.route('/detail/<int:id>', methods=['GET'])
def detail(id):
user = session.get('user_info')
if not user:
url = url_for('login')
return redirect(url)
info = USERS.get(id)
return render_template('detail.html', info=info)
# endpoint反向url解析, 必须唯一
@app.route('/login', methods=['GET', 'POST'], endpoint='login')
def login():
if request.method == 'GET':
return render_template('login.html')
else:
user = request.form.get('user')
pwd = request.form.get('pwd')
if user == 'huqi' and pwd == '123':
session['user_info'] = user
return redirect('/index')
return render_template('login.html', error="用户名或密码错误")
if __name__ == '__main__':
app.run()
2. login.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>用户登录</h1>
<form method="post">
<input type="text" name="user">
<input type="text" name="pwd">
<input type="submit" value="登录">{{error}}
</form>
</body>
</html>
3. index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<title>用户列表</title>
<h1>用户列表</h1>
<table>
{% for k,v in user_dict.items() %}
<tr>
<td>{{k}}</td>
<td>{{v.name}}</td>
<td>{{v.get('age')}}</td>
<td>{{v['gender']}}</td>
<td><a href="/detail/{{k}}">自我介绍</a></td>
</tr>
{% endfor %}
</table>
</body>
</html>
4. detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<h1>详细介绍 - {{info.name}}</h1>
<div>
{{info.text}}
</div>
</body>
</html>