FLASK学习记录-Flask表单(一)
Form表单是一个包含表单元素的区域,允许用户在表单中输入各种信息元素,是前后端交互的重要标签,Form标签常用属性如下:
常用表单控件:
实例:
app.py
from flask import Flask, render_template, request app = Flask(__name__) @app.route('/', methods=["get", "post"]) def index(): if request.method == "POST": user1 = request.form.get('visitorName') pwd1 = request.form.get('password') return "visitor: {},password{}....".format(user1, pwd1) if request.method == "GET": return render_template("form_1.html") if __name__ == '__main__': app.run(host='0.0.0.0',port=8000,debug=True)
form_1.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>form1</title> </head> <body> <form action="/" method="post"> <p> <label for="visitorName">访客登记名:</label><input type="text" name="visitorName" id="visitorName" placeholder="访客登记名"> </p> <p><label for="password">密 码:</label><input type="password" name="password" id="password" placeholder="密码"></p> <p> 性 别: <label><input type="radio" name="gender" value="male">男</label> <label><input type="radio" name="gender" value="female">女</label> </p> <p> 领 域: <input type="checkbox" name="hobby" value="program">文科 <input type="checkbox" name="hobby" value="music">理科 <input type="checkbox" name="hobby" value="photo">工科 <input type="checkbox" name="hobby" value="photo">文艺 <input type="checkbox" name="hobby" value="photo">声乐 </p> <p> 上传文件:<input type="file"> </p> <p>  址: <select name="addr" id=""> <!--select是有级别之分的,比如某某省某某市的--> <optgroup label="广东省"> <option value="sz">深圳</option> <!--selected 用来设置默认的城市--> <option value="gz" selected="selected">广州</option> </optgroup> <optgroup label="江西省"> <option value="nc">南昌</option> <option value="ja">吉安</option> </optgroup> </select> </p> <p> <fieldset> <legend>个人留言:</legend> <textarea name="profile" rows="5" cols="50"></textarea> </fieldset> </p> <p> <input type="submit" value="提交"> <input type="reset" value="重置"> </p> </form> </body> </html>
使用Flask-WTF
安装:pip install flask-wtf -i https://pypi.tuna.tsinghua.edu.cn/simple
WTForm常用字段,更多内容可参考官方文档 https://flask-wtf.readthedocs.io/en/1.2.x/
常用验证器
实例:
$ pip install email_validator -i https://pypi.tuna.tsinghua.edu.cn/simple
$ cat loginForm.py from flask_wtf import FlaskForm from wtforms import StringField,PasswordField from wtforms.validators import DataRequired,Length class loginForm(FlaskForm): username=StringField(label='用户名',validators=[DataRequired(message='用户名不能为空')],render_kw={'placeholder':'输入用户名'}) password=PasswordField(label='密码',validators=[DataRequired(),Length(8,12,message='lenth must between 8 and 12')])
$ cat registerForm.py from flask_wtf import FlaskForm from wtforms import StringField,PasswordField,SubmitField,IntegerField from wtforms.validators import DataRequired, Length, NumberRange, EqualTo, ValidationError,Email import email_validator import re class RegisterForm(FlaskForm): mobile = StringField(label='手机号', default='') email=StringField(label="邮箱",validators=[DataRequired('请输入密码'),Length(6,20),Email()]) password = PasswordField(label='密码', validators=[DataRequired('请输入密码'),EqualTo('conpwd',message="两次密码不一致")]) conpwd=PasswordField(label='确认密码', validators=[DataRequired('请再次输入密码')]) age = IntegerField(label='年龄',validators=[NumberRange(min=18,max=50)]) submit = SubmitField('注册') def validate_mobile(self, field): mobile= field.data pattern = r'^1[0-9]{10}$' if not re.search(pattern, mobile): raise ValidationError('手机号') return field
from flask import Flask, render_template, request from loginForm import loginForm from registerForm import RegisterForm app = Flask(__name__) @app.route('/', methods=["get", "post"]) def index(): if request.method == "POST": user1 = request.form.get('visitorName') pwd1 = request.form.get('password') return "visitor: {},password{}....".format(user1, pwd1) if request.method == "GET": return render_template("form_1.html") @app.route("/login", methods=["get", "post"]) def login(): if request.method == "GET": return render_template("login.html") else: login = loginForm(request.form) if login.validate(): return "success" else: return "pass" @app.route("/register",methods=["get", "post"]) def register(): form=RegisterForm() if form.validate_on_submit(): username = form.username.data email=form.email.data password = form.password.data conpwd=form.conpwd.data age = form.age.data print("手机号:{},Email:{},密码:{},确认密码:{},年龄:{}".format(username,email,password,conpwd,age)) else: print(form.errors) return render_template('register.html', form=form) if __name__ == '__main__': app.run(host='0.0.0.0',port=8000,debug=True)
login.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>login</title> </head> <body> <form action="/login" method="post"> <p> 用户名:<input type="text" name="username"> </p> <p> 密码:<input type="password" name="password"> </p> <p> <input type="submit" value="登录"> </p> </form> </body> </html>
register.html
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>register</title> </head> <body> <form action="{{ url_for('register') }}" method="post"> {{ form.csrf_token }} <p> {{ form.mobile.label }} {{ form.mobile}} {% if form.mobile.errors %} {% for err in form.mobile.errors %} <span>{{ err }}</span> {% endfor %} {% endif %} </p> <p> {{ form.email.label }} {{ form.email }} {% if form.email.errors %} {% for err in form.email.errors %} <span>{{ err }}</span> {% endfor %} {% endif %} </p> <p> {{ form.password.label }} {{ form.password }} </p> <p> {{ form.conpwd.label }} {{ form.conpwd }} </p> <p> {{ form.age.label }} {{ form.age }} </p> <p> {{ form.submit }} </p> </form> </body> </html>
问题说明:访问注册接口“:8000/register”报错,“RuntimeError: A secret key is required to use CSRF.” 是因为Flask-WTF默认提供对每个表单免受跨站请求伪造的保护,解决办法是在app.py设置密钥,例如: app.config['SECRET_KEY'] = '123456', 或者app.secret_key='123456'
Flask-WTF文件上传:
设置上传文件大小不超过3MB
app.config['MAX_CONTENT_LENGTH']=3*1024*1024