python中Flask Web 表单的使用方法介绍

网友投稿 357 2022-07-29


目录简介普通表单提交Flask-WTF基础使用Flask-WTF处理表单Flask消息闪现文件上传文件上传的另一种写法

简介

表单的操作是Web程序开发中最核心的模块之一,绝大多数的动态交互功能都是通过表单的形式实现的。本文会教大家实现简单的表单操作。

普通表单提交

在创建模板login.html页面中直接写form表单。

login.html

{% if method == 'GET' %}

请求方式:{{method}}

{% elif method == 'POST' %}

请求方式:{{method}}

用户名:{{ username }}

密码:{{ password }}

{% endif %}

接下来,在视图函数中获取表单数据

login.py

from flask import Flask, render_template, request​

app = Flask(__name__)​

# index 视图函数

@app.route('/login', methods=['GET', 'POST'])

def login():

context = dict()

if request.method == 'POST':

username = request.form['username']

password = request.form['password']

print(username, password)

context = {

'username': username,

'password': password,

}

context.update({'method': request.method})

else:

context.update({'method': request.method})

return render_template('login.html', **context)

@app.route('/')

def index():

return 'hello'

if __name__ == '__main__':

app.run(debug=True)

当我们点击提交之后,则会显示:

上面的实现方式是直接采用表单的提交方式。但是有个弊端,假如参数很多的情况下,后台也需要一一进行验证,每次都是先接收参数,再对参数进行校验的话,工作量就会非常的庞大,而且还会出现csrf攻击,这时我们就可以采用Flask-WTF来创建表单,从而避免上述弊端。

Flask-WTF基础

Flask-WTF的主要作用是对用户的请求数据进行验证。我们可以使用pip命令安装该依赖,

pip install flask-wtf

在flask web程序中,因为类FlaskForm由Flask-WTF拓展定义,所以可以从flask.wtf中导入FlaskForm。而字段和函数可以直接从WTForms包中导入,WTForms包中可以支持如下所示的HTML标准字段。

字段说明StringField表示文本字段TextAreaField表示多行文本字段PasswordField表示密码文本字段HiddenField表示隐藏文本字段DateField表示日期的文本字段DateTimeFiled表示时间的文本字段IntegerFiled表示整数类型的文本字段DecimalField表示Decimal类型的文本字段FloatFiled表示Float类型的文本字段RadioFiled表示单选框字段SelectFiled表示下拉列表字段

WTForm也包含验证器,它对表单字段进行验证,非常方便。

字段说明DataRequire检查输入的字段是否为空Email检查字段是否符合邮件格式的约定IPAddress在输入字段中验证IP地址Length验证输入字段中的字符串长度是否符合给定长度NumberRange验证给定范围内输入字段中的文字URL验证是否为合法的URL

使用Flask-WTF处理表单

编写两个视图函数,以及一个form表单类,用于注册以及跳转index页面。

login.py

from flask import Flask, render_template, redirect, url_for, session

from flask_wtf import FlaskForm

from wtforms import StringField, PasswordField, SubmitField

from wtforms.validators import DataRequired, EqualTo

app = Flask(__name__)

app.config["SECRET_KEY"] = "xhosd6f982yfhowefy29f"​

class RegisterForm(FlaskForm):

username = StringField(label="用户名", validators=[DataRequired('用户名不能为空')])

password = PasswordField(label="密码", validators=[DataRequired('密码不能为空')])

password_comfirm = PasswordField(label="确认密码", validators=[DataRequired('密码不能为空'), EqualTo('phttp://assword', '两次密码不一致')])

submit = SubmitField(label='提交')​

@app.route('/register', methods=['GET', 'POST'])

def register():

form = RegisterForm()

if form.validate_on_submit():

uname = form.username.data

pwd = form.password.data

pwd_com = form.password_comfirm.data

print(uname, pwd, pwd_com)

session['username'] = uname

return redirect(url_for('index'))

return render_template('register.html', form=form)

@app.route('/index')

def index():

username = session.get('username', '')

return 'hello %s' % username

if __name__ == '__main__':

app.run(debug=True)

接下来编写一个html模板文件,用于用户注册使用。

register.html

{{form.csrf_token}}

{{form.username.label}}

{{ form.username }}

{% for msg in form.username.errors %}

{{ msg }}

{% endfor %}

{{form.password.label}}

{{ form.password }}

{% for msg in form.password.errors %}

{{ msg }}

{% endfor %}

{{form.password_comfirm.label}}

{{ form.password_comfirm }}

{% for msg in form.password.errors %}

{{ msg }}

{% endfor %}

{{ form.submit }}

Flask消息闪现

在Flask框架中,方法flash()功能是实现消息闪现提示效果。Flask官方对闪现的解释是对用户的请求做出无刷新的响应。类似于Ajax的刷新效果。

举一个简单的例子,当用户通过表单发送完请求之后,假如用户名或者是密码输入错误,那么服务器就会返回错误的提示信息,并在表单页面上显示。

具体代码,如下所示:RjgkCiFA

login.py

from flask import Flask, flash, redirect, render_template, request, url_for

app = Flask(__name__)

app.secret_key = 'random string'

@app.route('/')

def index():

return render_template('index.html')

@app.route('/login', mhttp://ethods=['GET', 'POST'])

def login():

error = None

if request.method == 'POST':

if request.form['username'] != 'admin' or request.form['password'] != 'admin':

flash("用户名或密码错误")

else:

flash('登录成功')

return redirect(url_for('index'))

return render_template('login.html')

if __name__ == '__main__':

app.run(debug=True)

login.html

username

password

{% for message in get_flashed_messages() %}

{% if message %}

{{message}}

{% endif %}

{% endfor %}

index.html

{% with messages = get_flashed_messages() %}

{% if messages %}

{% for message in messages %}

{{ message }}

{% endfor %}

{% endif %}

{% endwith %}

login

上面的代码实现了URL的跳转,我们首先会进入首页,首页中包含了进入登录页面的链接。

文件上传

在Flas Web程序中要实现文件的上传非常简单,与传递post和get非常的类似。基本流程如下:

(1)将在客户端上传的文件保存到flask.request.files对象。(2)使用flask.request.files对象获取上传上来的文件名和文件对象(3)调用文件对象中的方法save()将文件保存到指定的目录中。

简易的文件上传程序如下所示:

upload.py

from flask import Flask, flash, render_template, request

app = Flask(__name__)

@app.route('/upload', methods=['GET', 'POST'])

def upload():

if request.method == 'GET':

return render_template('upload.html')

else:

file = request.files['file']

if file:

file.save(file.name + '.png')

return '上传成功'

@app.route('/')

def index():

return render_template('index.html')

if __name__ == '__main__':

app.run(debug=True)

index.html

文件上传

upload.html

本程序需要点击跳转之后才能进入文件上传页面,这样写的目的只是因为我比较懒,不想再浏览器中输入一大串的url。

目前上述程序仅仅可以上传图片!

文件上传的另一种写法

在Flask中上传文件的步骤非常简单,首先需要一个HTML表单,将enctype属性设置为"multipart/form-data"即可。URL处理程序会从request.file[]对象中提取文件,并将它保存到所需要的位置上。

每个上传的文件首先会保存到服务器上的临时位置,然后将其保存到最终的实际位置。建议使用secure_filename函数获取。

index.html

upload.py

from flask import Flask, render_template, request

from werkzeug.utils import secure_filename

import os

app = Flask(__name__)

app.config['UPLOAD_FLODER']= 'upload/' # 设置文件保存的路径

@app.route('/')

def upload_file():

return render_template('upload.html')

@app.route('/uploader', methods=['GET', 'POST'])

def uploader():

if request.method == 'POST':

f = request.files['file']

print(request.files)

f.save(os.path.join(app.config['UPLOAD_FLODER'], secure_filename(f.filename)))

return '上传成功'

else:

render_template('upload.html')

if __name__ == '__main__':

app.run(debug=True)


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:springboot读取nacos配置文件的实现(nacos spring boot)
下一篇:Spring详解使用注解开发流程(spring注解如何实现)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~