cookie
from flask import Flask, render_template, request, redirect, make_response app = Flask(__name__) user_list = ['wb', 'valentine', 'wb112232'] @app.route('/login/', methods=['GET','POST']) def login(): if request.method == 'POST': username = request.form['username'] if username in user_list: response = make_response(redirect('/index/')) response.set_cookie('username',value=username,max_age=300) return response else: return redirect('/login/') else: return render_template('login.html') @app.route('/index/') def index(): username=request.cookies['username'] if username: return render_template('index.html',username = username) else: return redirect('/login/') if __name__ == '__main__': app.debug = True app.run()
response.setcookie('key', 'value', max_age=n) n的单位为秒。
response.cookies.get['name']/response.cookies['name']获取cookie
将max_age设置为0,即为删除cookie。
Session
生成一个
app.secret_key
import os res = os.urandom(24)
后台
from flask import Flask, render_template, request, redirect, session app = Flask(__name__) app.secret_key='x18x0b6x96xeaPx8d"xc8x04xf6Gx8exae5x0fxf6xe1x89xc1}x04xa3x0c' user_list = ['wb', 'valentine', 'wb112232'] @app.route('/login/', methods=['GET','POST']) def login(): if request.method == 'POST': username = request.form['username'] if username in user_list: session['username']=username return redirect('/index/') else: return redirect('/login/') else: return render_template('login.html') @app.route('/index/') def index(): username=session['username'] if username: return render_template('index.html',username = username) else: return redirect('/login/') @app.route('/logout/') def logout(): pass if __name__ == '__main__': app.debug = True app.run()
cookie安全性差,session对服务器性能有影响,可将登陆信息存放于session