Python Web

《Flask Web开发实战》—— 表单

2020-01-05  本文已影响0人  北邮郭大宝

Flask关于表单处理的部分,使用Flask-WTF库,首先安装

pip install flask-wtf

1. 表单的基本处理

Flask中表单的基本处理步骤有:

1.1 定义表单类form.py

from flask_wtf import FlaskForm
from wtforms import StringField, PasswordField, BooleanField, SubmitField
from wtforms.validators import DataRequired, Length


class LoginForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(message=u'名字不能为空')])
    password = PasswordField('Password', validators=[DataRequired(), Length(6, 128)])
    remember = BooleanField('Remember me')
    submit = SubmitField('Log in')

通过继承FlaskForm类,可以定义自己的表单;此外validators可以添加常见的数据验证工具,比如DataRequired,Length等。

1.2 1.2 渲染表单basic.html

{% extends 'base.html' %}

{% block content %}
<div class="basic-body">
    <form method="post">
        {{ form.csrf_token }}
        <div class="form-group">
            {{ form.username.label }} {{ form.username }}
            {% for message in form.username.errors %}
                <small class="error">{{ message }}</small><br>
            {% endfor %}
        </div>
        <div class="form-group">
            {{ form.password.label }} {{ form.password }}
            {% for message in form.password.errors %}
                <small class="error">{{ message }}</small><br>
            {% endfor %}
        </div>
        <div class="form-check">
           {{ form.remember }} {{ form.remember.label }}
        </div>
        <div>
            {{ form.submit(class='btn btn-primary') }}
        </div>
    </form>
</div>
{% endblock content %}

1.3 处理表单数据app.py

@app.route('/basic', methods=['GET', 'POST'])
def basic():
    form = LoginForm()
    if form.validate_on_submit():
        username = form.username.data
        flash('Welcome home %s' % username)
        return redirect(url_for('index'))
    return render_template('basic.html', form=form)

1.4 效果

1578040441420.jpg

2. 使用宏渲染表单

使用宏可以简化渲染的过程,新建macors.html,定义宏

{% macro form_field(field) %}
    {{ field.label }}<br>
    {{ field(**kwargs) }}<br>
    {% if field.errors %}
        {% for error in field.errors %}
            <small class="error">{{ error }}</small><br>
        {% endfor %}
    {% endif %}
{% endmacro %}

在basic.html里渲染

{% extends 'base.html' %}
{% from 'macros.html' import form_field %}

{% block content %}
<h2>Basic BootStrap Style Form Example</h2>
<div class="basic-body">
    <form method="post">
        {{ form.csrf_token }}
        <div class="form-group">
            {{ form_field(form.username) }}
        </div>
        <div class="form-group">
            {{ form_field(form.password) }}
        </div>
        <div class="form-check">
            {{ form.remember }} {{ form.remember.label }}
        </div>
        <div>
             {{ form.submit(class='btn btn-primary') }}
        </div>
    </form>
</div>
{% endblock content %}

3. 自定义验证器

验证器除了validators提供的外,还这次自定义,比如定义is_42这个函数作为全局的验证器。

def is_42(message=None):
    if message is None:
        message = 'Must be 42'

    def _is_42(form, field):
        if field.data != 42:
            raise ValidationError(message)

    return _is_42


class FortyTwoForm(FlaskForm):
    answer = IntegerField('The Number', validators=[is_42()])
    submit = SubmitField()

4. 上传单文件

通过FileField实现,在form.py中定义UploadForm表单

from flask_wtf.file import FileField, FileRequired, FileAllowed

class UploadForm(FlaskForm):
    photo = FileField('Upload Image', validators=[FileRequired(), FileAllowed(['jpg', 'jpeg', 'png', 'gif'])])
    submit = SubmitField()

app.py中数据处理逻辑

#   上传单文件
@app.route('/upload', methods=['GET', 'POST'])
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        f = form.photo.data
        filename = random_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
        flash('Upload success!')
        session['filenames'] = [filename]
        return redirect(url_for('show_images'))
    return render_template('upload.html', form=form)
    
def random_filename(filename):
    ext = os.path.splitext(filename)[1]
    new_filename = uuid.uuid4().hex + ext
    return new_filename

upload.html中与之前的无疑,需要加的是enctype="multipart/form-data"

<form method="post", enctype="multipart/form-data">

5. 上传多文件

与单文件上传区别不大,改动有:

6. 单表单多按钮

class NewPostForm(FlaskForm):
    title = StringField('Title', validators=[DataRequired(), Length(1, 50)])
    body = TextAreaField('Body', validators=[DataRequired()])
    save = SubmitField('Save')
    publish = SubmitField('Publish')
#  单个表单多个提交按钮
@app.route('/two-submits', methods=['GET', 'POST'])
def two_submit():
    form = NewPostForm()
    if form.validate_on_submit():
        if form.save.data:
            flash("You click the save button.")
        elif form.publish.data:
            flash('You click the publis button')
        return redirect(url_for('index'))
    return render_template('2submit.html', form=form)

7. 单页面多表单

即一个页面中包含多个表单,处理方法有两种

7.1 单视图处理

处理逻辑是在定义表单类时,通过命名区别,比如submit1,submit2等

class SigninForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 128)])
    submit1 = SubmitField('Sign in')


class RegisterForm(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(1, 20)])
    email = StringField('Emails', validators=[DataRequired(), Length(1, 254), Email()])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 128)])
    submit2 = SubmitField('Register')
#  单个页面多个表单----单视图处理
@app.route('/multi-form', methods=['GET', 'POST'])
def multi_form():
    signin_form = SigninForm()
    register_form = RegisterForm()

    if signin_form.submit1.data and signin_form.validate_on_submit():
        username = signin_form.username.data
        flash('%s, you just submit sign in button' % username)
        return redirect(url_for('index'))

    if register_form.submit2.data and register_form.validate_on_submit():
        username = signin_form.username.data
        flash('%s, you just submit register button' % username)
        return redirect(url_for('index'))

    return render_template('2form.html', signin_form=signin_form, register_form=register_form)

7.2 多视图处理

处理逻辑是分离表单的渲染和验证实现。


class SigninForm2(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(1, 20)])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 128)])
    submit = SubmitField('Sign in')


class RegisterForm2(FlaskForm):
    username = StringField('Username', validators=[DataRequired(), Length(1, 20)])
    email = StringField('Emails', validators=[DataRequired(), Length(1, 254), Email()])
    password = PasswordField('Password', validators=[DataRequired(), Length(8, 128)])
    submit = SubmitField('Register')
#  单个页面多个表单----多视图处理
@app.route('/multi-form-multi-view')
def multi_form_multi_view():
    signin_form = SigninForm2()
    register_form = RegisterForm2()
    return render_template('2form2view.html', signin_form=signin_form, register_form=register_form)


@app.route('/handle-signin', methods=['POST'])
def handle_signin():
    signin_form = SigninForm2()
    register_form = RegisterForm2()

    if signin_form.validate_on_submit():
        username = signin_form.username.data
        flash('%s, you just submit sign in button' % username)
        return redirect(url_for('index'))

    return render_template('2form2view.html', signin_form=signin_form, register_form=register_form)


@app.route('/handle-register', methods=['POST'])
def handle_register():
    signin_form = SigninForm2()
    register_form = RegisterForm2()

    if register_form.validate_on_submit():
        username = register_form.username.data
        flash('%s, you just submit register button' % username)
        return redirect(url_for('index'))

    return render_template('2form2view.html', signin_form=signin_form, register_form=register_form)
<div class="basic-body">
    <h3>Sign In Form</h3>
    <form method="post", action="{{ url_for('handle_signin') }}">
        {{ signin_form.csrf_token }}
        <div class="form-group">
            {{ form_field(signin_form.username) }}
        </div>
        <div class="form-group">
            {{ form_field(signin_form.password) }}
        </div>
        <div>
             {{ signin_form.submit(class='btn btn-primary') }}
        </div>
    </form>
</div>
<div class="basic-body">
    <h3>Register Form</h3>
    <form method="post", action="{{ url_for('handle_register') }}">
        {{ register_form.csrf_token }}
        <div class="form-group">
            {{ form_field(register_form.username) }}
        </div>
        <div class="form-group">
            {{ form_field(register_form.email) }}
        </div>
        <div class="form-group">
            {{ form_field(register_form.password) }}
        </div>
        <div>
            {{ register_form.submit(class='btn btn-primary') }}
        </div>
    </form>
</div>

8. 总结

详细代码,请参考GitHub

上一篇下一篇

猜你喜欢

热点阅读