重定向
刷新页面时浏览器会重新发送之前发送过的请求。如果前一个请求是包含表单数据的POST请求,刷新页面后会再次提交表单。多数情况下,这并不是我们想执行的操作,因此浏览器才要求用户确认
原理:会向重定向的URL发起GET请求,显示页面的内容
缺点:加载时间变长
hello.py
from flask import Flask, render_template, session, redirect, url_for
@app.route('/', methods=['GET', 'POST'])
def index():
name = None
form = NameForm()
if form.validate_on_submit():
name = form.name.data
return redirect(url_for('index')) # post请求后使用重定向方式
return render_template('index.html', form=form, name=name)
用户会话
使用重定向后,原form.name.data数据为空,无法形成完成响应。
用户会话是一种私有存储,每个连接到服务器的客户端都可访问
from flask import Flask, render_template, session, redirect, url_for
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
session['name'] = form.name.data
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'))
会话取值
- session[‘name’] 当不存在name字段时,程序报错
- session.get(‘name’) 当不存在name字段时, 返回None
消息闪现
请求完成后,有时需要让用户知道状态发生了变化,可以是确认消息、警告或者错误提醒
视图函数
hello.py
from flask import Flask, render_template, session, redirect, url_for, flash
@app.route('/', methods=['GET', 'POST'])
def index():
form = NameForm()
if form.validate_on_submit():
old_name = session['name']
if old_name and old_name != form.name.data:
flash("looks like you changed your name")
session['name'] = form.name.data
return redirect(url_for('index'))
return render_template('index.html', form=form, name=session.get('name'))
模板渲染
base.html
{% block content %}
<div class="container">
{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
<button type="button" class="close" data-dismiss="alert">×</button>
{{ message }}
</div>
{% endfor %}
{% block page_content %}{% endblock %}
</div>
{% endblock %}