flask中的wtforms使用方法

时间:2022-11-21 10:08:54

一、简单介绍flask中的wtforms

wtforms是一个支持多个web框架的form组件,主要用于对用户请求数据进行验证。

安装:

?
1
pip3 install wtforms

二、简单使用wtforms组件

1、用户登录

flask中的wtforms使用方法

具体代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
from flask import flask,render_template,request,redirect
from wtforms.fields import core
from wtforms.fields import html5
from wtforms.fields import simple
from wtforms import form
from wtforms import validators
from wtforms import widgets
app = flask(__name__,template_folder="templates")
 
class myvalidators(object):
  '''自定义验证规则'''
  def __init__(self,message):
    self.message = message
  def __call__(self, form, field):
    print(field.data,"用户输入的信息")
    if field.data == "haiyan":
      return none
    raise validators.validationerror(self.message)
 
class loginform(form):
  '''form'''
  name = simple.stringfield(
    label="用户名",
    widget=widgets.textinput(),
    validators=[
      myvalidators(message="用户名必须是haiyan"),#也可以自定义正则
      validators.datarequired(message="用户名不能为空"),
      validators.length(max=8,min=3,message="用户名长度必须大于%(max)d且小于%(min)d")
    ],
    render_kw={"class":"form-control"} #设置属性
  )
 
  pwd = simple.passwordfield(
    label="密码",
    validators=[
      validators.datarequired(message="密码不能为空"),
      validators.length(max=8,min=3,message="密码长度必须大于%(max)d且小于%(min)d"),
      validators.regexp(regex="\d+",message="密码必须是数字"),
    ],
    widget=widgets.passwordinput(),
    render_kw={"class":"form-control"}
  )
 
 
 
@app.route('/login',methods=["get","post"])
def login():
  if request.method =="get":
    form = loginform()
    return render_template("login.html",form=form)
  else:
    form = loginform(formdata=request.form)
    if form.validate():
      print("用户提交的数据用过格式验证,值为:%s"%form.data)
      return "登录成功"
    else:
      print(form.errors,"错误信息")
    return render_template("login.html",form=form)
 
 
if __name__ == '__main__':
  # app.__call__()
  app.run(debug=true)

login.html

?
1
2
3
4
5
6
7
8
9
10
<body>
<form action="" method="post" novalidate>
  <p>{{ form.name.label }} {{ form.name }} {{ form.name.errors.0 }}</p>
  <p>{{ form.pwd.label }} {{ form.pwd }} {{ form.pwd.errors.0 }}</p>
  <input type="submit" value="提交">
  <!--用户名:<input type="text">-->
  <!--密码:<input type="password">-->
  <!--<input type="submit" value="提交">-->
</form>
</body>

2、用户注册

flask中的wtforms使用方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
from flask import flask,render_template,redirect,request
from wtforms import form
from wtforms.fields import core
from wtforms.fields import html5
from wtforms.fields import simple
from wtforms import validators
from wtforms import widgets
 
app = flask(__name__,template_folder="templates")
app.debug = true
 
=======================simple===========================
class registerform(form):
  name = simple.stringfield(
    label="用户名",
    validators=[
      validators.datarequired()
    ],
    widget=widgets.textinput(),
    render_kw={"class":"form-control"},
    default="haiyan"
  )
  pwd = simple.passwordfield(
    label="密码",
    validators=[
      validators.datarequired(message="密码不能为空")
    ]
  )
  pwd_confim = simple.passwordfield(
    label="重复密码",
    validators=[
      validators.datarequired(message='重复密码不能为空.'),
      validators.equalto('pwd',message="两次密码不一致")
    ],
    widget=widgets.passwordinput(),
    render_kw={'class': 'form-control'}
  )
 
  ========================html5============================
  email = html5.emailfield( #注意这里用的是html5.emailfield
    label='邮箱',
    validators=[
      validators.datarequired(message='邮箱不能为空.'),
      validators.email(message='邮箱格式错误')
    ],
    widget=widgets.textinput(input_type='email'),
    render_kw={'class': 'form-control'}
  )
 
  ===================以下是用core来调用的=======================
  gender = core.radiofield(
    label="性别",
    choices=(
      (1,"男"),
      (1,"女"),
    ),
    coerce=int #限制是int类型的
  )
  city = core.selectfield(
    label="城市",
    choices=(
      ("bj","北京"),
      ("sh","上海"),
    )
  )
  hobby = core.selectmultiplefield(
    label='爱好',
    choices=(
      (1, '篮球'),
      (2, '足球'),
    ),
    coerce=int
  )
  favor = core.selectmultiplefield(
    label="喜好",
    choices=(
      (1, '篮球'),
      (2, '足球'),
    ),
    widget = widgets.listwidget(prefix_label=false),
    option_widget = widgets.checkboxinput(),
    coerce = int,
    default = [1, 2]
  )
 
  def __init__(self,*args,**kwargs): #这里的self是一个registerform对象
    '''重写__init__方法'''
    super(registerform,self).__init__(*args, **kwargs) #继承父类的init方法
    self.favor.choices =((1, '篮球'), (2, '足球'), (3, '羽毛球')) #吧registerform这个类里面的favor重新赋值
 
  def validate_pwd_confim(self,field,):
    '''
    自定义pwd_config字段规则,例:与pwd字段是否一致
    :param field:
    :return:
    '''
    # 最开始初始化时,self.data中已经有所有的值
    if field.data != self.data['pwd']:
      # raise validators.validationerror("密码不一致") # 继续后续验证
      raise validators.stopvalidation("密码不一致") # 不再继续后续验证
 
@app.route('/register',methods=["get","post"])
def register():
  if request.method=="get":
    form = registerform(data={'gender': 1}) #默认是1,
    return render_template("register.html",form=form)
  else:
    form = registerform(formdata=request.form)
    if form.validate(): #判断是否验证成功
      print('用户提交数据通过格式验证,提交的值为:', form.data) #所有的正确信息
    else:
      print(form.errors) #所有的错误信息
    return render_template('register.html', form=form)
 
if __name__ == '__main__':
  app.run()

register.html

?
1
2
3
4
5
6
7
8
9
<body>
<h1>用户注册</h1>
<form method="post" novalidate style="padding:0 50px">
  {% for item in form %}
  <p>{{item.label}}: {{item}} {{item.errors[0] }}</p>
  {% endfor %}
  <input type="submit" value="提交">
</form>
</body>

3、meta

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import flask, render_template, request, redirect, session
from wtforms import form
from wtforms.csrf.core import csrf
from wtforms.fields import core
from wtforms.fields import html5
from wtforms.fields import simple
from wtforms import validators
from wtforms import widgets
from hashlib import md5
 
app = flask(__name__, template_folder='templates')
app.debug = true
 
 
class mycsrf(csrf):
  """
  generate a csrf token based on the user's ip. i am probably not very
  secure, so don't use me.
  """
 
  def setup_form(self, form):
    self.csrf_context = form.meta.csrf_context()
    self.csrf_secret = form.meta.csrf_secret
    return super(mycsrf, self).setup_form(form)
 
  def generate_csrf_token(self, csrf_token):
    gid = self.csrf_secret + self.csrf_context
    token = md5(gid.encode('utf-8')).hexdigest()
    return token
 
  def validate_csrf_token(self, form, field):
    print(field.data, field.current_token)
    if field.data != field.current_token:
      raise valueerror('invalid csrf')
 
 
class testform(form):
  name = html5.emailfield(label='用户名')
  pwd = simple.stringfield(label='密码')
 
  class meta:
    # -- csrf
    # 是否自动生成csrf标签
    csrf = true
    # 生成csrf标签name
    csrf_field_name = 'csrf_token'
 
    # 自动生成标签的值,加密用的csrf_secret
    csrf_secret = 'xxxxxx'
    # 自动生成标签的值,加密用的csrf_context
    csrf_context = lambda x: request.url
    # 生成和比较csrf标签
    csrf_class = mycsrf
 
    # -- i18n
    # 是否支持本地化
    # locales = false
    locales = ('zh', 'en')
    # 是否对本地化进行缓存
    cache_translations = true
    # 保存本地化缓存信息的字段
    translations_cache = {}
 
 
@app.route('/index/', methods=['get', 'post'])
def index():
  if request.method == 'get':
    form = testform()
  else:
    form = testform(formdata=request.form)
    if form.validate():
      print(form)
  return render_template('index.html', form=form)
 
 
if __name__ == '__main__':
  app.run()

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。

原文链接:https://www.cnblogs.com/haiyan123/p/8254228.html