欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

flask中的wtforms使用方法

 更新時間:2018年07月21日 17:24:25   作者:海燕。  
這篇文章主要介紹了flask中的wtforms使用方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

一、簡單介紹flask中的wtforms

WTForms是一個支持多個web框架的form組件,主要用于對用戶請求數(shù)據(jù)進行驗證。

安裝:

pip3 install wtforms

二、簡單使用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):
  '''自定義驗證規(guī)則'''
  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"} #設(shè)置屬性
  )

  pwd = simple.PasswordField(
    label="密碼",
    validators=[
      validators.DataRequired(message="密碼不能為空"),
      validators.Length(max=8,min=3,message="密碼長度必須大于%(max)d且小于%(min)d"),
      validators.Regexp(regex="\d+",message="密碼必須是數(shù)字"),
    ],
    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("用戶提交的數(shù)據(jù)用過格式驗證,值為:%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="重復(fù)密碼",
    validators=[
      validators.DataRequired(message='重復(fù)密碼不能為空.'),
      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來調(diào)用的=======================
  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字段規(guī)則,例:與pwd字段是否一致
    :param field:
    :return:
    '''
    # 最開始初始化時,self.data中已經(jīng)有所有的值
    if field.data != self.data['pwd']:
      # raise validators.ValidationError("密碼不一致") # 繼續(xù)后續(xù)驗證
      raise validators.StopValidation("密碼不一致") # 不再繼續(xù)后續(xù)驗證

@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('用戶提交數(shù)據(jù)通過格式驗證,提交的值為:', 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()

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • python實現(xiàn)linux下抓包并存庫功能

    python實現(xiàn)linux下抓包并存庫功能

    這篇文章主要為大家詳細介紹了python實現(xiàn)linux下抓包并存庫功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • Python響應(yīng)對象text屬性亂碼解決方案

    Python響應(yīng)對象text屬性亂碼解決方案

    這篇文章主要介紹了Python響應(yīng)對象text屬性亂碼解決方案,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-03-03
  • python中的字典詳細介紹

    python中的字典詳細介紹

    這篇文章主要介紹了python中的字典詳細介紹,字典是Python中最強大的數(shù)據(jù)類型之一,本文講解了什么是字典、創(chuàng)建字典和給字典賦值 、字典的基本操作、映射類型操作符、映射相關(guān)的函數(shù)、字典的方法等內(nèi)容,需要的朋友可以參考下
    2014-09-09
  • 淺析Python中字符串的intern機制

    淺析Python中字符串的intern機制

    這篇文章主要介紹了Python中字符串的intern機制,幫助大家更好的理解和學(xué)習(xí)python,感興趣的朋友可以了解下
    2020-10-10
  • python協(xié)程異步IO中asyncio的使用

    python協(xié)程異步IO中asyncio的使用

    這篇文章主要介紹了python異步編程之a(chǎn)syncio的使用,python中異步IO操作是通過asyncio來實現(xiàn)的,為了更加詳細說明asyncio,我們先從協(xié)程的最基礎(chǔ)開始講解
    2023-12-12
  • python之json文件轉(zhuǎn)xml文件案例講解

    python之json文件轉(zhuǎn)xml文件案例講解

    這篇文章主要介紹了python之json文件轉(zhuǎn)xml文件案例講解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-08-08
  • python實現(xiàn)控制電腦鼠標和鍵盤,登錄QQ的方法示例

    python實現(xiàn)控制電腦鼠標和鍵盤,登錄QQ的方法示例

    這篇文章主要介紹了python實現(xiàn)控制電腦鼠標和鍵盤,登錄QQ的方法,涉及Python基于Button,Controller,Key模塊針對鍵盤、鼠標的控制相關(guān)操作技巧,需要的朋友可以參考下
    2019-07-07
  • 解決tensorflow打印tensor有省略號的問題

    解決tensorflow打印tensor有省略號的問題

    今天小編就為大家分享一篇解決tensorflow打印tensor有省略號的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-02-02
  • python基礎(chǔ)之遞歸函數(shù)

    python基礎(chǔ)之遞歸函數(shù)

    這篇文章主要介紹了python遞歸函數(shù),實例分析了Python中返回一個返回值與多個返回值的方法,需要的朋友可以參考下
    2021-10-10
  • Python語法學(xué)習(xí)之線程的創(chuàng)建與常用方法詳解

    Python語法學(xué)習(xí)之線程的創(chuàng)建與常用方法詳解

    本文主要介紹了線程的使用,線程是利用進程的資源來執(zhí)行業(yè)務(wù),并且通過創(chuàng)建多個線程,對于資源的消耗相對來說會比較低,今天就來看一看線程的使用方法具體有哪些吧
    2022-04-04

最新評論