Flask第三集
Flask_WTF扩展可以处理web表单。使用Flask-WTF时,每个Web表单都由一个继承自Form的类表示。
表单类
使用Flask——WTF时,每个Web表单都由有个继承自Form的类表示,这个类定义表单中的一组字段,每个字段都用对象表示,字段对象可附属一个或者多个验证函数。验证函数用来验证用户提交的输入值是否符合要求。
示例:定义表单类
from flask.ext.wtf import Form
from wtforms import StringField,SubmitField
from wtforms.validators import Required
class NameForm(Form):
name=StringField('What is your name?',validators=[Required()])
submit=SubmitField('Submit')
在这个示例中,NameForm表单中有一个名为name的文本字段和一个名为submit的提交按钮,StringField类表示属性为type="text"的<iuput>元素,SubmitField类表示属性为type="submit"的<iuput>元素
字段构造函数的第一个参数是把表单渲染成HTML时使用的标号。
把表单渲染成HTML
在模板中调用表单字段后会渲染成HTML。
示例:试图函数把一个NameForm实例通过参数form 传入模板
<form method="POST">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name() }}
{{ form.submit() }}
</form>
示例:把参数传入渲染字段的函数
<form method="POST">
{{ form.hidden_tag() }}
{{ form.name.label }} {{ form.name(id='my-text-field') }}
{{ form.submit() }}
</form>
示例:使用Flask-WTF和Flask-Bootstrap渲染表单
{% entends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}Flasky{% endblock %}
{% block page_content %}
<div class="page-header">
<h1>Hello,{% if name %}{{ name }}{% else %}Stranger{% endif %}!</h1>
</div>
{{ wtf.quick_form(form) }}
{% endblock %}
在视图函数中处理表单
视图函数不仅套渲染表单,还要接收表单中的数据
示例:路由方法
@app.route('/',methods=['GET','POST'])
def index():
name=None
form=NameForm()
if form.validate_on_submit():
name=form.name.date
form.name.date=''
return render_template('index.html',form=form,name=name)
app.route修饰器中添加的methods参数告诉Flask在URL映射中把这个视图函数注册为GET和POST请求的处理程序。如果没指定methods参数,就只把试图函数注册为GET请求的处理程序。
重定向和用户会话
示例:hello.py重定向和用户会话
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'))
redirect()函数的参数是重定向的URL。
Flash消息
请求完成后,有时需要让用户知道状态发生了变化。
示例:hello.pyFlash消息
from flask import Flask,render_tempalte,session,redirect,url_for,flash
@app.route('/',methods=['GET','POST'])
def index():
form=NameForm()
if form.validate_on_submit():
old_name=session.get('name')
if form.validate_on_submit():
old_name=session.get('name')
if old_name is not None and old_name != form.name.data:
flash('Looks like you have changed your nam!')
session['name']=form.name.data
return redirect(url_for('index'))
return render_tempalte('index.html',form=form,name=session.get('name'))
示例:渲染Flash消息
{% block content %}
<div class="container">
{% for message in get_flashed_messages() %}
<div class="alert alert-warning">
<button type="button" class="close" date-dismiss="alert">×</button>
{{ message }}
</div>
{% endfor %}
{% block page_content %}{% endbock %}
</div>
{% endblcok %}