from flask import Flask, session, redirect, url_for, escape, request app = Flask(__name__) @app.route(‘/‘) def index(): #判断username是否存在session中 if ‘username‘ in session: return ‘Logged in as %s‘ % escape(session[‘username‘]) return ‘You are not logged in‘ @app.route(‘/login‘, methods=[‘GET‘, ‘POST‘]) def login(): if request.method == ‘POST‘: #设置session username为输入的表单值 session[‘username‘] = request.form[‘username‘] #重定向到首页 return redirect(url_for(‘index‘)) return ‘‘‘ <form action="" method="post"> <p><input type=text name=username> <p><input type=submit value=Login> </form> ‘‘‘ @app.route(‘/logout‘) def logout(): # 移除一个username session session.pop(‘username‘, None) return redirect(url_for(‘index‘)) #设置一个安全key app.secret_key = ‘A0Zr98j/3yX R~XHH!jmN]LWX/,?RT‘ app.run()
时间: 2024-10-10 23:19:05