重定向

刷新页面时浏览器会重新发送之前发送过的请求。如果前一个请求是包含表单数据的POST请求,刷新页面后会再次提交表单。多数情况下,这并不是我们想执行的操作,因此浏览器才要求用户确认
原理:会向重定向的URL发起GET请求,显示页面的内容
缺点:加载时间变长

hello.py

  1. from flask import Flask, render_template, session, redirect, url_for
  2. @app.route('/', methods=['GET', 'POST'])
  3. def index():
  4. name = None
  5. form = NameForm()
  6. if form.validate_on_submit():
  7. name = form.name.data
  8. return redirect(url_for('index')) # post请求后使用重定向方式
  9. return render_template('index.html', form=form, name=name)

用户会话

使用重定向后,原form.name.data数据为空,无法形成完成响应。
用户会话是一种私有存储,每个连接到服务器的客户端都可访问

  1. from flask import Flask, render_template, session, redirect, url_for
  2. @app.route('/', methods=['GET', 'POST'])
  3. def index():
  4. form = NameForm()
  5. if form.validate_on_submit():
  6. session['name'] = form.name.data
  7. return redirect(url_for('index'))
  8. return render_template('index.html', form=form, name=session.get('name'))

会话取值

  • session[‘name’] 当不存在name字段时,程序报错
  • session.get(‘name’) 当不存在name字段时, 返回None

    消息闪现

    请求完成后,有时需要让用户知道状态发生了变化,可以是确认消息、警告或者错误提醒

视图函数

hello.py

  1. from flask import Flask, render_template, session, redirect, url_for, flash
  2. @app.route('/', methods=['GET', 'POST'])
  3. def index():
  4. form = NameForm()
  5. if form.validate_on_submit():
  6. old_name = session['name']
  7. if old_name and old_name != form.name.data:
  8. flash("looks like you changed your name")
  9. session['name'] = form.name.data
  10. return redirect(url_for('index'))
  11. return render_template('index.html', form=form, name=session.get('name'))

模板渲染

base.html

  1. {% block content %}
  2. <div class="container">
  3. {% for message in get_flashed_messages() %}
  4. <div class="alert alert-warning">
  5. <button type="button" class="close" data-dismiss="alert">&times;</button>
  6. {{ message }}
  7. </div>
  8. {% endfor %}
  9. {% block page_content %}{% endblock %}
  10. </div>
  11. {% endblock %}

image.png