处理利用cookie来判断用户登录外,也可以使用session来判断用户是否登录
html代码和cookie对象的设置相同
from flask import Flask,request,render_template,make_response,session,url_for,redirectapp=Flask(__name__)
app.secret_key='ps1234567890'
@app.route('/')
def index():#判断cookie是否存在if session.get('logged_in'):return '欢迎来到首页'else:return '请先登录'@app.route('/login',methods=['GET','POST'])
def login():#验证表单数据if request.method=='POST':username=request.form['username']password=request.form['password']if username=='mrsoft' and password=='psword':#如果用户名和密码正确,写入cookiesession['logged_in']=Truereturn redirect(url_for('index'))return render_template('login.html')@app.route('/logout')
def logout():session.pop('logged_in')return redirect(url_for('login'))if __name__=='__main__':app.run(debug=True,port=8000)