系统环境:Ubuntu 18.04.1 LTS
Python使用的是虚拟环境:virutalenv
Python的版本:Python 3.6.9
【简说Python WEB】Form提交表单
B/S架构的核心,一个get数据,另外一个post数据。很多交互性的网站,都需要通过Form表单来向服务器提交数据。这里介绍,简单做一个From表单。感受一下post数据和与服务器端的交互。
安装flask-wtf
pip install flask-wtf
代码树
├── app.py
└── templates
├── 404.html
├── 500.html
├── base.html
└── index.html
app.py
源码中表单类:
设置一个密钥,是防止表单遭到跨站请求伪造(CSRF).保证其安全。会生成一个令牌,加密签名的。
app.config['SECRET_KEY'] = 'wojiubugaosuni'
这里的
wojiubugaosuni
不能明文写入配置文件,应该通过环境变量传入,保证安全性。
添加了一个FlaskForm
表格。表格中有如下字段 :
- 一个
name
的文本字段,其中StringField
构造函数中的validators
的参数,确保提交的字段不能为空。 - 一个名为
submit
的按钮
from flask_wtf import FlaskForm
from wtforms import StringField, SubmitField
from wtforms.validators import DataRequired
class NameForm(FlaskForm):
name = StringField('你的名字叫什么', validators=[DataRequired()])
submit = SubmitField('Submit')
index.html
的源码修改:渲染form表单
{% extends "base.html" %}
{% import "bootstrap/wtf.html" as wtf %}
{% block title %}zsdblog{% endblock %}
{% block content %}
<div class="container">
<div class="page-header">
<h1>您好, {{ name }},欢迎来到我的博客!</h1>
</div>
</div>
{{ wtf.quick_form(form) }}
{% endblock %}
其中添加了{% import "bootstrap/wtf.html" as wtf %}
和{{ wtf.quick_form(form) }}
使用bootstrap来渲染form表单元素。
app.py
源码中from表单处理
@app.route('/', methods=['GET', 'POST'])
def index():
name = '游客'
form = NameForm()
if form.validate_on_submit():
name = form.name.data
form.name.data = ''
return render_template('index.html', form=form, name=name)
效果演示:
输入小明
之后的演示效果:
不输入任何字符,会触发StringField
构造函数中的验证效果:
就会有请填写此字段
的验证效果
会话和重定向
提交表单之后,按F5
刷新浏览器,会报出一个警告。如下页面:
为了让数据保持,就保存在一个session
之中。修改app.py
代码如下 :
from flask import Flask, render_template,session,redirect,url_for
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_for('index'))