app.secret_key = 'Xqw1UfUwQV6LVfxY3y5Oc3c0ji/zkEW7loXqznZbXNU='
密鑰應該足夠隨機,這裏咱們能夠經過uuid來生成:html
In [1]: import base64,uuid In [2]: base64.b64encode(uuid.uuid4().bytes+uuid.uuid4().bytes).decode() Out[2]: 'bMSQkw+tTWCiJTiCpogsc3V3Ai/s/0Eam5/2btXAg7g='
from flask import Flask, session, redirect, url_for, escape, request,render_template from datetime import timedelta app = Flask(__name__) app.secret_key = 'Xqw1UfUwQV6LVfxY3y5Oc3c0ji/zkEW7loXqznZbXNU=' @app.route('/') def index(): if 'username' in session: return '登陸用戶:%s' % escape(session['username']) return '您還沒有登陸!' @app.route('/login', methods=['GET', 'POST']) def login(): if request.method == 'POST': session.permanent = True app.permanent_session_lifetime = timedelta(days=1) #設置會話過時時間爲1天
session['username'] = request.form['username'] return redirect(url_for('index')) return render_template('login.html') @app.route('/logout') def logout(): session.pop('username', None) return redirect(url_for('index')) if __name__ == "__main__": app.run()
escape()函數是對字符串進行轉義flask