以下是登录和登出的逻辑
@app.route('/login', methods=['GET', 'POST'])
def login():
if request.method == 'POST':
username = request.form['username']
password = request.form['password']
if username == 'admin' and password == 'admin':
session['logged_in'] = True
session['username'] = username
flash("登陆成功")
return redirect(url_for('novel_index'))
else:
return 'Invalid username or password'
return redirect(url_for('novel_index'))
@app.route('/logout', methods=['GET', 'POST'])
def logout():
session.pop('logged_in', None)
session.pop('username', None)
return redirect(url_for('novel_index'))
在登录后设置了session会话值
session['logged_in'] = True
在网页中获取这个值需要使用
{% if session.logged_in %}
实际案例如下
{% if session.logged_in %}
<!-- 登录表单,实际上用户已经登录,所以可以显示欢迎信息或其他内容 -->
<form class="navbar-form pull-right" action="/logout" method="post">
<button type="submit" class="btn">Logout</button>
</form>
{% else %}
<!-- 登录表单 -->
<form class="navbar-form pull-right" action="/login" method="post">
<input class="span2" type="text" name="username" placeholder="Username">
<input class="span2" type="password" name="password" placeholder="Password">
<button type="submit" class="btn">Sign in</button>
</form>
{% endif %}
发表回复