web.py
from flask import Flask,request,render_template,redirect,session
app = Flask(__name__)
app.config['SECRET_KEY']='youhappyisgood' #app.secret_key 修改的时候会造成cookie失效 默认cookie有效1个月 推荐使用flask_session配合redis使用
admin = {'username':'zycdn','password':'zycdn'}
STUDENT_DICT = {
1: {'name': '张三', 'age': 18, 'gender': '中'},
2: {'name': '李四', 'age': 38, 'gender': '男'},
3: {'name': '王五', 'age': 28, 'gender': '女'},
}
# 除了Login函数之外的所有函数,全校验 session 是否登录了
@app.before_request
def is_login():
if request.path=='/login':
return None
username = session.get('username')
if not username:
return redirect('/login')
@app.route('/login',methods=['GET','POST'])
def login():
if request.method == "POST":
username = request.form.get('username')
password = request.form.get('password')
if username == admin['username'] and password == admin.get('password'):
session['username'] = username
return redirect('/stus')
else:
return render_template('login.html',msg='登录失败')
return render_template('login.html',msg='')
@app.route('/stus')
def stus():
# 由is_login完成session验证
# if not session.get('username'):
# return redirect('/login')
return render_template('stus.html',stus=STUDENT_DICT)
@app.route('/stu')
def stu():
# 由is_login完成session验证
# if not session.get('username'):
# return redirect('/login')
id = int(request.args.get('id'))
return render_template('stu.html',stu = STUDENT_DICT[id],stuid=id)
if __name__ == '__main__':
app.run(host='0.0.0.0',port=5000,debug=True)
login.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>登录title>
head>
<body>
<form method="POST">
<p>用户<input type="text" name="username">p>
<p>密码<input type="password" name="password">p>
<p><input type="submit" value="提交">p>
{{ msg }}
form>
body>
html>
stus.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>学生列表title>
head>
<body>
{% for index in stus %}
{{index}} -- {{stus[index].get('name')}} -- <a href='stu?id={{index}}'>详细a> <br/>
{% endfor %}
body>
html>
stu.html
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>学生信息title>
head>
<body>
{{stuid}}--{{stu.get('name')}}--{{stu['age']}}--{{stu.gender}}<br/>
<a href='/stus'>返回a>
body>
html>
session:eyJ1c2VybmFtZSI6Inp5Y2RuIn0.XwgysA.xddxYB-MoAfCfMoAFLqvv7IBP_Q