flask 의 wtforms 사용 방법

10339 단어 flaskwtforms
1.fllask 의 wtforms 를 간단하게 소개 합 니 다.
WTForms 는 여러 웹 프레임 워 크 를 지원 하 는 form 구성 요소 로 사용자 요청 데 이 터 를 검증 하 는 데 사 용 됩 니 다.
설치:

pip3 install wtforms
2.wtforms 구성 요 소 를 간단하게 사용 합 니 다.
1.사용자 로그 인

구체 적 인 코드:

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

<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.사용자 등록

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

<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

#!/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()
이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기