美文网首页js css html
Flask 入门-(三)Form表单提交

Flask 入门-(三)Form表单提交

作者: 侠之大者_7d3f | 来源:发表于2022-01-30 18:14 被阅读0次

    前言

    在web程序中,form表单应用广泛, 比如用户登录, 像QQ登录这种的实现。本文采用Flask实现简单的Form表单提交的demo。

    最终效果:


    image.png

    测试环境

    • Ubuntu20.04/win11
    • Flask
    • VSCode

    Flask Form表单实现

    一般的Form表单实现

    一般在HTML中, form表单采用<form></form> 标签进行定义, 在form标签中加入<inuput></input>标签:

        <form action="#" method="post">
            <div>
                <label for="username">Username</label>
                <input type="text" name="username" id="" placeholder="input username">
            </div>
            <div>
                <label for="pwd">Password</label>
                <input type="text" name="pwd" id="" placeholder="input password">
            </div>
            <input type="submit" value="submit">
        </form>
    

    Flask中Form表单的实现

    在Flask中,一般不采用上面那种方式,Flask提供了一些扩展 Flask-WTFwtforms, Flask中一般对Form表单的操作采用Flask-WTF实现。

    pip install flask-wtf
    

    wtforms 提供了Form表单常用的控件:

    • fields: StringField, PasswordField, BooleanField, SubmitField, 用于生成<input>标签
    • validators: 验证器, 验证输入是否合法
        "DataRequired",
        "data_required",
        "Email",
        "email",
        "EqualTo",
        "equal_to",
        "IPAddress",
        "ip_address",
        "InputRequired",
        "input_required",
        "Length",
        "length",
        "NumberRange",
        "number_range",
        "Optional",
        "optional",
        "Regexp",
        "regexp",
        "URL",
        "url",
        "AnyOf",
        "any_of",
        "NoneOf",
        "none_of",
        "MacAddress",
        "mac_address",
        "UUID",
        "ValidationError",
        "StopValidation",
    

    flask-wtf扩展包提供了一个类: FlaskForm, 一般自定义的Form都要继承这个FlaskForm。
    注意: 由于浏览器具有cookies功能,为了Form表单提交的安全性考虑, Form表单提交的时候需要指定CSRF令牌, 需要在Flask中设置 SECRET_KEY

    app.config['SECRET_KEY'] = 'hello-flask'   # RuntimeError: A secret key is required to use CSRF.
    

    SECRET_KEY的值是随机的字符串。

    Flask Form表单的具体应用步骤:

    • Step1: 自定义Form类,继承FlaskForm
    class LoginForm(FlaskForm):
        username = StringField(label='Username', validators=[DataRequired(), Length(1, 30)])
        password = PasswordField(label='Password', validators=[DataRequired(), Length(4, 10)])
        remember = BooleanField(label='Remember me')
        submit = SubmitField(label='Login')
    
    • Step2: 配置视图函数,实例化form对象, 并且将form对象传递给render_template()函数
      一般Form表单提交采用POST请求, 因此需要在路由里面设置 methods='POST'
    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = LoginForm()
        if form.validate_on_submit():
            global username
            global pwd
            username = form.username.data
            pwd = form.password.data
            # 重定向为GET请求
            return redirect((url_for('success')))
        return render_template('index.html', form=form)
    
    • Step3: 在HTML中渲染Form,生成Form标签。
      为了美观以及易用性考虑,Form表单的渲染使用 bootstrap-flask进行渲染。
      bootstrap: Twitter公司开源的前端框架,提供了bootstrap.css和bootstrap.mini.css, 包含了常用的css样式,在开发的时候不用过多考虑样式问题。
      bootstrap-flask: Flask的一个python扩展,就是对bootstrap进行了封装,在HTML中的用法和bootstrap用法相同。

    pip install bootstrap-flask

    bootstrap-flask的使用过程:
    加载bootstrap的CSS文件(这里直接采用CDN加载, 也可以下载到本地进行加载) ---> 使用Jinja2语法导入render_form()宏函数 ---> 使用render_form()渲染传入的form对象。

       {{ bootstrap.load_css() }}
       {% from 'bootstrap/form.html' import render_form  %}
    
        <main class="container">
            {{ render_form(form=form, form_type="basic") }}
            {{ bootstrap.load_js() }}
        </main>
    

    关于render_form()宏函数:

    {# valid form types are "basic", "inline" and "horizontal" #}
    {% macro render_form(form,
                        action="",
                        method="post",
                        extra_classes=None,
                        role="form",
                        form_type="basic",
                        horizontal_columns=('lg', 2, 10),
                        enctype=None,
                        button_map={},
                        button_style="",
                        button_size="",
                        id="",
                        novalidate=False,
                        render_kw={}) %}
    

    测试工程

    目录结构

    文件目录结构非常简单,没有包含CSS/JS文件,只有HTML模板。


    image.png

    代码实现

    • app.py
    from flask import Flask, render_template, url_for, redirect, flash
    from flask_bootstrap import Bootstrap
    from wtforms import StringField, PasswordField, BooleanField, SubmitField
    from flask_wtf import FlaskForm
    from wtforms.validators import DataRequired, Length
    
    # https://bootstrap-flask.readthedocs.io/en/latest/
    
    class LoginForm(FlaskForm):
        username = StringField(label='Username', validators=[DataRequired(), Length(1, 30)])
        password = PasswordField(label='Password', validators=[DataRequired(), Length(4, 10)])
        remember = BooleanField(label='Remember me')
        submit = SubmitField(label='Login')
    
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = 'hello-flask'   # RuntimeError: A secret key is required to use CSRF.
    bootstrap = Bootstrap(app=app)  # 初始化bootstrap
    
    username = None
    pwd = None
    
    @app.route('/login_success')
    def success():
        flash(message=username)
        flash(message=pwd)
        return render_template('success.html')
    
    
    @app.route('/', methods=['GET', 'POST'])
    def index():
        form = LoginForm()
        if form.validate_on_submit():
            global username
            global pwd
            username = form.username.data
            pwd = form.password.data
            # 重定向为GET请求
            return redirect((url_for('success')))
        return render_template('index.html', form=form)
    app.run()
    
    • index.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>flask_form</title>
        {{ bootstrap.load_css() }}
        {% from 'bootstrap/form.html' import render_form  %}
    </head>
    <body>
        <main class="container">
            {{ render_form(form=form, form_type="basic") }}
            {{ bootstrap.load_js() }}
        </main>
    </body>
    </html>
    
    • success.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>flask_form</title>
        {{ bootstrap.load_css() }}
    </head>
    <body>
        <main class="container">
            {% for message in get_flashed_messages() %}
                {{ message }}
            {% endfor %}
            {{ bootstrap.load_js() }}
        </main>
    </body>
    </html>
    

    运行结果:


    image.png image.png

    观察bootstrap-flask生成的HTML, 打开浏览器调试窗口,可以看到HTML代码:

    
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>flask_form</title>
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
        
    </head>
    <body>
        <main class="container">
            
        <form action="" method="post"
                class="form" role="form">
            <input id="csrf_token" name="csrf_token" type="hidden" value="IjZiYzNjZTFiODg3NTA3OTBjMmNiYmI1ODBjYjkwODM4MWQxYWI3NGYi.Yfa-Xg.Fg_26W5499T3niSfJzvmdvIA_w8">
        <div class="form-group required">
            <label class="form-control-label" for="username">Username</label>
            <input class="form-control" id="username" maxlength="30" minlength="1" name="username" required type="text" value="">      
        </div>
        <div class="form-group required">
            <label class="form-control-label" for="password">Password</label>
           <input class="form-control" id="password" maxlength="10" minlength="4" name="password" required type="password" value="">       
        </div>
            
        <div class="form-group form-check"><input class="form-check-input" id="remember" name="remember" type="checkbox" value="y">
            <label class="form-check-label" for="remember">Remember me</label>
        </div>
        <input class="btn btn-primary btn-md" id="submit" name="submit" type="submit" value="Login">
        </form>
            <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
            <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js" integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN" crossorigin="anonymous"></script>
            <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.min.js" integrity="sha384-VHvPCCyXqtD5DqJeNxl2dtTyhF78xXNXdkwX1CZeRusQfRKp+tA7hAShOK/B/fQ2" crossorigin="anonymous"></script>
        </main>
    </body>
    </html>
    
    1. bootstrap-flask 的 render_form()宏函数在渲染form表单时候自动会添加 CSRF令牌<input id="csr_token" name="csrf_token" type="hidden" value="IjZiYzNjZTFiODg3NTA3OTBjMmNiYmI1ODBjYjkwODM4MWQxYWI3NGYi.Yfa-Xg.Fg_26W5499T3niSfJzvmdvIA_w8">

    2. 当采用默认CDN时候bootstrap-flask 会自动加载 jquery.js, popper.js, bootstrap.min.js 这3个JavaScript

    相关文章

      网友评论

        本文标题:Flask 入门-(三)Form表单提交

        本文链接:https://www.haomeiwen.com/subject/kvoqkrtx.html