1.添加模板文件login.html
<formcheck') }}">
用户名:<input>
<input>
</form>
2.视图函数
# 登陆
@app.route('/login/', methods=['GET', 'POST'])
def login():
return render_template('login.html')
# 校验
@app.route('/check/', methods=['GET', 'POST'])
def check():
return '登陆成功, %s~' % request.form['username']
3.将登陆页面和校验的路由合并
@app.route('/login/', methods=['GET', 'POST'])
def login():
if request.method == 'GET':
return render_template('login.html')
return '登陆成功, %s~' % request.form['username']
一个路由处理时,表单的action属性不用书写
1.说明
是一个用于表单处理的扩展库,提供了CSRF、校验等功能,使用非常方便。
2.安装
pip install flask-wtf
3.使用
# 原生渲染
# 导入表单基类
from flask_wtf import FlaskForm
# 导入相关类型
from wtforms import StringField, SubmitField
# 导入验证器
from wtforms.validators import DataRequired
# CSRF需要
app.config['SECRET_KEY'] = 'idandan'
# 定义表单类
class NameForm(FlaskForm):
name = StringField('账号:', validators=[DataRequired()])
submit = SubmitField('登陆')
@app.route('/formTest/')
def formTest():
# 创建表单对象
form = NameForm()
return render_template('formTest.html', form = form)
# html
<form>
{{ form.hidden_tag() }}
{{ form.name .label()}} {{ form.name(id = 'username', class = 'username') }}
{{ form.submit }}
</form>
# bootstrap渲染
# 设置bootstrap本地库中的文件
app.config['BOOTSTRAP_SERVER_LOCAL'] = True
# html
{% extends 'bootstrap/base.html' %}
{# 导入 #}
{% import 'bootstrap/wtf.html' as wtf %}
{% block title %}
表单渲染
{% endblock %}
{% block content %}
<div>
{{ wtf.quick_form(form) }}
</div>
{% endblock %}
4.表单校验
@app.route('/formTest/', methods=['GET', 'POST'])
def formTest():
# 创建表单对象
form = NameForm()
# return render_template('formTest.html', form = form)
# return render_template('bootForm.html', form = form)
# 表单校验
name = None
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
return render_template('bootForm.html', form = form, name = name)
# html
{% extends 'bootstrap/base.html' %}
{# 导入 #}
{% import 'bootstrap/wtf.html' as wtf %}
{% block title %}
表单渲染
{% endblock %}
{% block content %}
<h1>
Hi,
{% if name %}
{{ name }}!
{% else %}
Stranger!
{% endif %}
</h1>
<div>
{{ wtf.quick_form(form) }}
</div>
{% endblock %}
5.POST重定向GET
@app.route('/formTest/', methods=['GET', 'POST'])
def formTest():
# 创建表单对象
form = NameForm()
# 表单校验
name = None
if form.validate_on_submit():
session['name'] = form.name.data
form.name.data = ''
return redirect(url_for('formTest'))
name = session.get('name')
return render_template('bootForm.html', form = form, name = name)
6.常见的字段类型
7.常见验证器类
8.自定义字段验证
# 定义表单类
class NameForm(FlaskForm):
name = StringField('账号:', validators=[DataRequired()])
submit = SubmitField('登陆')
# 自定义字段验证函数,格式是写一个‘valudate_字段名’函数
def validate_name(self, field):
if len(field.data) < 6:
raise ValidationError('账号长度不能小于6个字符')
1.说明
当用户请求发出后,用户状态发生了改变,需要给出提示、警告等信息时,通常可以通过弹窗的形式给出指示,用户可以跟据提示进行下一步操作,也可手动取消显示。
2.使用
在合适的时候书写flash消息,调用flash函数
@app.route('/formTest/', methods=['GET', 'POST'])
def formTest():
# 创建表单对象
form = NameForm()
# return render_template('formTest.html', form = form)
# return render_template('bootForm.html', form = form)
# 表单校验
name = None
if form.validate_on_submit():
oldName = session.get('name')
if oldName is not None and oldName != form.name.data:
flash('Change your name!')
session['name'] = form.name.data
return redirect(url_for('formTest'))
name = session.get('name')
return render_template('bootForm.html', form = form, name = name)
# html
{% for message in get_flashed_messages() %}
<h3>{{ message }}</h3>
{% endfor %}
若好多页面都有弹出消息,可以将flash消息放在基础模板中展示。
1.说明
专门负责时间本地化显示的扩展库,使用非常方便 。
2.安装
pip install flask-moment
3.使用
# 导入类库
from flask_moment import Moment
# 创建对象
moment = Moment(app)
from datetime import datetime, timedelta
@app.route('/moment/')
def moment():
current_time = datetime.utcnow() + timedelta(seconds=-3600) # 伪造时间
return render_template('moment.html', current_time=current_time)
# HTML
{#{% extends 'bootstrap/base.html' %}#}
{% block content %}
<div>
<h1>时间本地化显示</h1>
<h3>距离:{{ moment(current_time).fromNow() }}</h3>
<h3>时间:{{ moment(current_time).format('LLLL') }}</h3>
</div>
{% endblock %}
{#加载jquery和moment,因为moment.js需要依赖,使用bootstrap时就不需要再加载jquery#}
{{ moment.include_jquery() }}
{{ moment.include_moment() }}