""" 1. 设置session # 设置session成功 重定向到首页 session.permanent = True # 设置会话过期时间 session['info'] = username return redirect(url_for('index')) 2. 获取session info = session.get('info', default=0) return render_template('index.html', info=info) 3. 设置session会话有效期 1. session.permanent = True # 设置会话过期时间 2. # 两种设置会话有效期时间方法 # app.permanent_session_lifetime = datetime.timedelta(days=2) # 会话有效期2天 app.permanent_session_lifetime = 60 * 60 * 24 * 7 # 会话有效期7天 4. 删除session # 删除会话 session.pop('info', None) return redirect(url_for('login')) """
python
import datetime
from flask import Flask, render_template, redirect, url_for, request, session, make_response, Response
from functools import wraps
def auth(fn):
@wraps(fn)
def inner(*args, **kwargs):
if not session.get('info', None):
return redirect(url_for('login'))
return fn(*args, **kwargs)
return inner
app = Flask(__name__)
app.secret_key = "ghakjhkghkahkhgkhalkfdngkasnkglhaj"
# 两种设置会话有效期时间方法
# app.permanent_session_lifetime = datetime.timedelta(days=2) # 会话有效期2天
app.permanent_session_lifetime = 60 * 60 * 24 * 7 # 会话有效期7天
print(app.url_map)
@app.route('/')
@app.route('/index', methods=["GET", "POST"])
@auth
def index():
# 获取会话
info = session.get('info', default=0)
return render_template('index.html', info=info)
@app.route('/login', methods=["GET", "POST"])
def login():
if request.method == "POST":
username = request.form.get('username', None)
password = request.form.get('password', None)
confirm_password = request.form.get('confirm_password', None)
if not username or not password or not confirm_password:
return render_template('login.html', errors="不能为空")
elif not username:
return render_template('login.html', errors="用户名有误")
elif password != confirm_password:
return render_template('login.html', errors="密码不一致")
elif username == "root" and password == "123":
# 设置session成功 重定向到首页
session.permanent = True # 设置会话过期时间
session['info'] = username
return redirect(url_for('index'))
else:
return render_template('login.html', errors="账号或密码有误")
return render_template('login.html')
@app.route('/logout', methods=["GET", "POST"])
@auth
def logout():
# 删除会话
session.pop('info', None)
return redirect(url_for('login'))
@app.route('/test')
@auth
def test():
return "测试"
if __name__ == '__main__':
app.run(debug=True)