python学习笔记(三)-表单处理

发布时间:2019-09-02 07:55:44编辑:auto阅读(1612)

    表单类
    默认情况下,Flask-WTF能保护所有表单免受跨站请求伪造攻击(CSRF)

    app = Flask(__name__)
    # 强制性必须填写secret_key
    app.config['SECRET_KEY'] = 'hard to guess string'

    定义表单

    from flask_wtf import Form
    from wtforms import StringField, SubmitField
    from wtforms.validators import Required
    class NameForm(Form):
        name = StringField('What is your name', validators=[DataRequired()])
        submit = SubmitField('Submit')

    Form基类由Flask-WTF扩展定义,所以从flask_wtf中导入,字段和验证函数却可以直接从WTForms中导入
    NameForm表单中有一个名为name的文本段和一个名为submit的提交按钮。StringField类表示属性为type=’text’的input元素。SubmitField类表示属性为type=”submit”的input元素。
    效果为

    WTForms支持的HTML标准如下所示

    把表单渲染成html template/index.html

    {% extends "base.html" %}
    {% import "bootstrap/wtf.html" as wtf %}
    {% block title %} Flasky {% endblock %}
    {%  block page_content %}
        <div class="page-hearder">
            <h1>Hello,{% if name %}{{ name }}{% else %}Stranger{% endif %}</h1>
        </div>
        {{ wtf.quick_form(form) }}
    {% endblock %}

    视图函数中处理表单

    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = NameForm()
        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 name!')
            session['name'] = form.name.data
            return redirect(url_for('index'))
        return render_template('index.html', form=form, name=session.get('name'))
    

    加入Flash消息,修改base.html,加入get_flashed_messages()消息处理

    {% 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 %}

    最终效果如图所示

    本文参考《Flask Web开发-基于Python的Web应用开发实战》

关键字