美文网首页flask学习
Flask-表单学习

Flask-表单学习

作者: 你就像只铁甲小宝 | 来源:发表于2019-02-16 15:40 被阅读4次

    第一种方式,使用html写的表单


    1.设置路由,和视图函数

     常用的html表单
    @app.route('/form_1')
    def form_1():
        return render_template('forms/forms_1.html')
    

    2.来编写forms_1.html文件

    <form method="post">
    <label for="username">Username</label><br>
    <input type="text" name="username" placeholder="Héctor Rivera"><br>
    <label for="password">Password</label><br>
    <input type="password" name="password" placeholder="19001130"><br>
    <input id="remember" name="remember" type="checkbox" checked>
    <label for="remember"><small>Remember me</small></label><br>
    <input type="submit" name="submit" value="Log in">
    </form>
    

    第二种方式,用Flask-wft渲染表单


    1.安装,然后在主模块中设置秘钥

    安装:
    pip install Flask-wtf

    设置秘钥,字符串随便设置,在实际中用的是随机值。:
    app.secret_key = 'secret string'

    2.然后要构造一个表单函数

    forms.py

    from flask_wtf import FlaskForm
    from flask_wtf.file import FileRequired, FileAllowed
    from wtforms import StringField, PasswordField, BooleanField, SubmitField, IntegerField, FileField
    from wtforms.validators import DataRequired, Length, ValidationError
    
    
    class LoginForm(FlaskForm):
        username = StringField('Username', validators=[DataRequired()])
        password = PasswordField('Password', validators=[DataRequired(), Length(8)])
        remember = BooleanField('Remember me')
        submit = SubmitField(' Log in ')
    

    validators里的是验证器:DataRequired()验证要有数据,Length验证长度。

    3.最后主模块中引入,编写函数。

    from forms import LoginForm
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    # 使用Flask-wtf渲染的表单
    @app.route('/basic', methods=['GET', 'POST'])
    def basic():
        form = LoginForm()
        # vlidate_on_submit:数据有效且为post请求返回True,反之False.
        if form.validate_on_submit():
            username = form.username.data
            flash(f'welcome home,{username}')
            return redirect(url_for('index'))
        return render_template('forms/login.html', form=form)
    
    • 若为post请求,验证数据,重定向到index页面,利用flash闪现出消息,'welcome home,xxxx'
    • 若为get请求,渲染login.html模板

    4. 编写html页面:

    login.html

    <form method="post">
    {{ form.csrf_token }} <!-- 渲染CSRF令牌隐藏字段 -->
    {{ form.username.label }}{{ form.username }}<br>
    {% for message in form.username.errors %}
        <small class="error" style="color:red">{{ message }}</small><br>
    {% endfor%}
    {{ form.password.label }}{{ form.password }}<br>
        {%for message in form.password.errors%}
            <small class="error" style="color:red">{{ message }}</small>
        <br>
        {% endfor %}
    {{ form.remember }}{{ form.remember.label }}<br>
    {{ form.submit }}<br>
    </form>
    
    • form.username.label:显示标签,form.username:输入框
    • form.xxx.errors:当输入错误时,显示的错误提醒,一般用for循环遍历。

    index.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    {% for message in get_flashed_messages()%}
            <div >{{ message }}</div>
    {% endfor %}
    </body>
    </html>
    

    5.结果:

    图片.png
    图片.png

    表单上传


    1.先在本地创建一个uploads文件夹,然后在主模块中设置参数

    # >>> app.root_path
    # 'C:\\Users\\Administrator\\PycharmProjects\\flask-form'
    app.config['UPLOAD_PATH'] = os.path.join(app.root_path, 'uploads')
    

    2. 同样的,我们需要编写上传的表单函数。

    forms.py

    class UploadForm(FlaskForm):
        photo = FileField('upload Image', validators=[FileRequired(), FileAllowed])
        submit = SubmitField()
    

    3. 编写视图函数

    app.py

    @app.route('/upload', methods=['GET', 'POST'])
    def upload():
        form = UploadForm()
        if form.validate_on_submit():
            f = form.photo.data
            # f:<FileStorage: 'timg.jpg' ('image/jpeg')>
            filename = f.filename
            print(filename)
            # 保存到/uploads目录下
            f.save(os.path.join(app.config['UPLOAD_PATH'], filename))
            flash('Upload success.')
            # 把filename保留到会话中。
            session['filenames'] = [filename]
            print(session['filename'])
            return redirect(url_for('show_images'))
        return render_template('upload.html', form=form)
    
    @app.route('/show_images')
    def show_images():
        return render_template('show_images.html')
    

    4.编写html页面

    show_images.html

    </head>
    <body>
    {% for message in get_flashed_messages()%}
            <div >{{ message }}</div>
    {% endfor %}
    <img src="{{ url_for('get_file', filename=session.filename[0]) }}" width="50%" height="50%">
    {{ session.filename[0] }}
    </body>
    </html>
    

    这里为了获取图片,编写了一个get_flie视图函数来获取图片。

    app.py

    @app.route('/uploads/<path:filename>')
    def get_file(filename):
         # C:\Users\Administrator\PycharmProjects\flask-form\uploads timg.jpg
        print(app.config['UPLOAD_PATH'], filename)
        return send_from_directory(app.config['UPLOAD_PATH'], filename)
    

    upload.html

    <!DOCTYPE html>
    {% from 'macros.html' import form_field %}
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
    </head>
    <body>
    <form method="post" enctype="multipart/form-data">
        {{ form.csrf_token}}
        {{ form.photo.label}}{{form.photo}}
        {{form.submit }}
    </form>
    
    </body>
    </html>
    

    5.结果:

    图片.png
    图片.png

    感觉这些都是熟能生巧的活,还要多学多练哈哈哈。


    相关文章

      网友评论

        本文标题:Flask-表单学习

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