flask--Wtform

来源:https://www.cnblogs.com/mengqingjian/archive/2018/01/10/8260570.html
-Advertisement-
Play Games

一、Wtform WTForms是一個支持多個web框架的form組件,主要用於對用戶請求數據進行驗證。 安裝: pip3 install wtform 用途: 1. 用戶登錄註冊 當用戶登錄時候,需要對用戶提交的用戶名和密碼進行多種格式校驗。如: 用戶不能為空;用戶長度必須大於6; 用戶不能為空; ...


一、Wtform

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

安裝:

   pip3 install wtform

用途:

 1. 用戶登錄註冊

 

       當用戶登錄時候,需要對用戶提交的用戶名和密碼進行多種格式校驗。如:

 

       用戶不能為空;用戶長度必須大於6;

 

       密碼不能為空;密碼長度必須大於12;密碼必須包含 字母、數字、特殊字元等(自定義正則);

 

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from flask import Flask, render_template, request, redirect
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


class LoginForm(Form):
    name = simple.StringField(
        label='用戶名',
        validators=[
            validators.DataRequired(message='用戶名不能為空.'),
            validators.Length(min=6, max=18, message='用戶名長度必須大於%(min)d且小於%(max)d')
        ],
        widget=widgets.TextInput(),
        render_kw={'class': 'form-control'}

    )
    pwd = simple.PasswordField(
        label='密碼',
        validators=[
            validators.DataRequired(message='密碼不能為空.'),
            validators.Length(min=8, message='用戶名長度必須大於%(min)d'),
            validators.Regexp(regex="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[$@$!%*?&])[A-Za-z\d$@$!%*?&]{8,}",
                              message='密碼至少8個字元,至少1個大寫字母,1個小寫字母,1個數字和1個特殊字元')

        ],
        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('用戶提交數據通過格式驗證,提交的值為:', form.data)
        else:
            print(form.errors)
        return render_template('login.html', form=form)

if __name__ == '__main__':
    app.run()

app.py
app.py

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<h1>登錄</h1>
<form method="post">
    <!--<input type="text" name="name">-->
    <p>{{form.name.label}} {{form.name}} {{form.name.errors[0] }}</p>

    <!--<input type="password" name="pwd">-->
    <p>{{form.pwd.label}} {{form.pwd}} {{form.pwd.errors[0] }}</p>
    <input type="submit" value="提交">
</form>
</body>
</html>
login

2.用戶註冊

       註冊頁面需要讓用戶輸入:用戶名、密碼、密碼重覆、性別、愛好等。

from flask import Flask, render_template, request, redirect
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



class RegisterForm(Form):
    name = simple.StringField(
        label='用戶名',
        validators=[
            validators.DataRequired()
        ],
        widget=widgets.TextInput(),
        render_kw={'class': 'form-control'},
        default='alex'
    )

    pwd = simple.PasswordField(
        label='密碼',
        validators=[
            validators.DataRequired(message='密碼不能為空.')
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    pwd_confirm = simple.PasswordField(
        label='重覆密碼',
        validators=[
            validators.DataRequired(message='重覆密碼不能為空.'),
            validators.EqualTo('pwd', message="兩次密碼輸入不一致")
        ],
        widget=widgets.PasswordInput(),
        render_kw={'class': 'form-control'}
    )

    email = html5.EmailField(
        label='郵箱',
        validators=[
            validators.DataRequired(message='郵箱不能為空.'),
            validators.Email(message='郵箱格式錯誤')
        ],
        widget=widgets.TextInput(input_type='email'),
        render_kw={'class': 'form-control'}
    )

    gender = core.RadioField(
        label='性別',
        choices=(
            (1, ''),
            (2, ''),
        ),
        coerce=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):
        super(RegisterForm, self).__init__(*args, **kwargs)
        self.favor.choices = ((1, '籃球'), (2, '足球'), (3, '羽毛球'))

    def validate_pwd_confirm(self, field):
        """
        自定義pwd_confirm欄位規則,例:與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})
        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()
APP.py
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<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>
</html>
register.html metaclass分析:

 

class MyType(type):
    def __init__(self,*args,**kwargs):
        print('xxxx')
        super(MyType,self).__init__(*args,**kwargs)

    def __call__(cls, *args, **kwargs):
        obj = cls.__new__(cls,*args, **kwargs)
        cls.__init__(obj,*args, **kwargs) # Foo.__init__(obj)
        return obj

def with_metaclass(base):
    return MyType("MyType",(base,),{})

class Foo(with_metaclass(object)):
    def __init__(self,name):
        self.name = name

 

class Form(with_metaclass(FormMeta, BaseForm)):   #相當於給這個form類定義了一個makeclass,這個類在剛創建時,先執行makeclass,這行makeclass的__init__方法
        pass


def with_metaclass(meta, base=object):
     #meta=FormMeta(("NewBase", (BaseForm,), {}))    #實例化了這個類
     #base=BaseForm   (base繼承了BaseForm)
    return meta("NewBase", (base,), {})
class LoginForm(Form):    #當執行到這一句是,他在formdata這個類中,LoginForm這個類中 裡邊有(LoginForm._unbound_fields = None
        LoginForm._wtforms_meta = None這兩個欄位)
    name=simple.StringField(           #name實例化一個StringField(如果這個name中有makeclass這個類先要執行makeclass這個類,一個類在實例化__init__之前 有__new__,__call__,type,這幾個方法,
對一個類來說整個請求進來先執行type的__init__方法,實例化的時候先執行type的__call__方法,有type的__call__方法調用類的 __new__方法,然後在執行類的__init__方法,這才叫實例化完成。對與這個StringField類方法,
如果有__new__方法,先執行__new__方法,點擊進去找到它的new方法,最開始寫的是StringField但正真的最開始是name=UnboundField(cls, *args, **kwargs)
(name對應的是UnboundField)在這個UnboundField中封裝creation_counter,它就等於當前creation_counter自加1)
label='用戶名', validators=[ validators.DataRequired(message='用戶名不能為空'), validators.Length(min=5,max=15,message='用戶名的長度必須大於5且小於15') ], widget=widgets.TextInput(), render_kw={'class':'form-control'} ) pwd=simple.PasswordField( #(在執行這個是pwd=UnboundField(cls, *args, **kwargs)但是當他執行時UnboundField中的creation_counter這個靜態欄位已經被更新,
用creation_counter這個來計數是因為跟你以後在頁面上顯示的次序有關係)
label='密碼', validators=[ validators.DataRequired(message='密碼不能為空'), validators.Length(min=6,max=15,message='密碼的長度必須大於6且小於15') ], widget=widgets.TextInput(), render_kw={'class':'form-control'} )

 

 

3.Wtform源碼分析

form類

 

from wtforms import Form

 

欄位功能:(1.通過正則進行校驗;2.插件生成HTML標簽

from wtforms.fields import core
from wtforms.fields import html5
from wtforms.fields import simple

插件

from wtforms import widgets

from wtforms import validators

源碼:

    代碼剛開始運行時:先執行LoginForm這個類的欄位開始實例化

    LoginForm 繼承From,這個類是有type創建 ,預設makeclass=type     (makeclass可以自定義)

 流程:

from flask import Flask,request,render_template,redirect

from wtforms import Form
from wtforms import widgets
from wtforms import validators

from wtforms.fields import core
from wtforms.fields import simple
from wtforms.fields import html5

app = Flask(__name__)

class LoginForm(Form):
    name=simple.StringField(
        label='用戶名',
        validators=[
            validators.DataRequired(message='用戶名不能為空'),
            validators.Length(min=5,max=15,message='用戶名的長度必須大於5且小於15')
        ],
        widget=widgets.TextInput(),
        render_kw={'class':'form-control'}
    )
    pwd=simple.PasswordField(
        label='密碼',
        validators=[
            validators.DataRequired(message='密碼不能為空'),
            validators.Length(min=6,max=15,message='密碼的長度必須大於6且小於15')
        ],
        widget=widgets.TextInput(),
        render_kw={'class':'form-control'}
    )


@app.route('/login',methods=['GET','POST'])
def login():
#程式剛進來是get請求,對
if request.method=='GET':
#程式剛進來是get請求先實例化form=LoginForm(),先執行type的__call__方法(有__call__就執行,沒有就跳過不執行,它的內部執行了接下來執行LoginForm
的__new__方法,再走LoginForm de __init__方法)

#頁面標簽數據初始化:data=字典,obj=對象.欄位,formdata有getlist方法 form
=LoginForm() return render_template('login.html',form=form) else: form=LoginForm(formdata=request.form) if form.validate(): print('用戶提交的數據通過格式驗證,提交的值為:',form.data) else: print(form.errors) return render_template('login.html',form=form) if __name__ == '__main__': app.run()
“先執行__call__方法” 

   def __call__(cls, *args, **kwargs):
        """
        Construct a new `Form` instance.

        Creates the `_unbound_fields` list and the internal `_wtforms_meta`
        subclass of the class Meta in order to allow a proper inheritance
        hierarchy.
        """
        if cls._unbound_fields is None:
            fields = []
            for name in dir(cls):   #(cls是LoginForm這個類,dir把這個類的所有欄位都拿到)
                if not name.startswith('_'):   #(判斷如果以'_'開頭)
#獲取靜態欄位的值:Unbound_Field對象 unbound_field
= getattr(cls, name) #(拿到Unbound_Field的對象
if hasattr(unbound_field, '_formfield'):
fields.append((name, unbound_field))
#(fields這個列表裡面是一個元組,元組裡面一個是它的名稱,一個是它的Unbound_field對象,每個
Unbound_field對象有creation_counter用來計數)
# We keep the name as the second element of the sort 
# to ensure a stable sort.
fields.sort(key=lambda x: (x[1].creation_counter, x[0])) #優先按照Unbound_field的count數來排序 ,fieldsshi 排序過後的欄位
cls._unbound_fields
= fields
# Create a subclass of the 'class Meta' using all the ancestors.
if cls._wtforms_meta is None: bases = []
for mro_class in cls.__mro__: #找到所有的繼承關係,相當於繼承所有的類
if 'Meta' in mro_class.__dict__: #mro_class.dict__ 就是;類中的所有成員
bases.append(mro_class.Meta)
cls._wtforms_meta
= type('Meta', tuple(bases), {}) #type('Meta')表示。自己創建一個Meta類繼承bases

return type.__call__(cls, *args, **kwargs)

 

'執行login的__new__方法,沒有__new__方法執行它的__init__方法'


def __init__(self, formdata=None, obj=None, prefix='', data=None, meta=None, **kwargs):

meta_obj = self._wtforms_meta() #原來創建的Meta類(實例化meta)
if meta is not None and isinstance(meta, dict):
meta_obj.update_values(meta)
super(Form, self).__init__(self._unbound_fields, meta=meta_obj, prefix=prefix)

for name, field in iteritems(self._fields):
# Set all the fields to attributes so that they obscure the class
# attributes with the same names.
setattr(self, name, field)
self.process(formdata, obj, data=data, **kwargs)


class BaseForm(object):
    """
    Base Form Class.  Provides core behaviour like field construction,
    validation, and data and error proxying.
    """

    def __init__(self, fields, prefix='', meta=DefaultMeta()):
        """
        :param fields:
            A dict or sequence of 2-tuples of partially-constructed fields.
        :param prefix:
            If provided, all fields will have their name prefixed with the
            value.
        :param meta:
            A meta instance which is used for configuration and customization
            of WTForms behaviors.
        """
        if prefix and prefix[-1] not in '-_;:/.':
            prefix += '-'

        self.meta = meta
        self._prefix = prefix
        self._errors = None
        self._fields = OrderedDict()

        if hasattr(fields, 'items'):
            fields = fields.items()

        translations = self._get_translations()
        extra_fields = []
        if meta.csrf:
            self._csrf = meta.build_csrf(self)
            extra_fields.extend(self._csrf.setup_form(self))

        for name, unbound_field in itertools.chain(fields, extra_fields):
            options = dict(name=name, prefix=prefix, translations=translations)
#對每一個UNbound中的欄位進行實例化 field
= meta.bind_field(self, unbound_field, options) self._fields[name] = field
get執行完現在開始校驗    
def validate(self):
        """
        Validates the form by calling `validate` on each field, passing any
        extra `Form.validate_<fieldname>` validators to the field validator.
        """
        extra = {}
        for name in self._fields:   #_fields是所有的欄位
            inline = getattr(self.__class__, 'validate_%s' % name, None)
            if inline is not None:
                extra[name] = [inline]

        return super(Form, self).validate(extra)   #調用父類的validate

 

 

 

你覺得基礎知識那些最重要函數也重要, 裝飾器,閉包也是蠻重要的。mainxiang面向對象基礎流程也是挺重要的,為什麼,因為它的流程我知道是

通過流程type,__call__,__new__再到這個方法,原來不知道,後來通過看了看源碼就瞭解了。 

 

 

 

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1.PHP錯誤級別 E_ERROR嚴重錯誤,腳本終止執行 E_WARNING警告,非嚴重錯誤,腳本繼續執行 E_NOTICE提示,不是很重要 代碼實例 結果 可以看到在NOTICE 和 WARNING之後,語句繼續執行,而ERROR之後的語句就沒有執行,如果將第5行的代碼換到第1行那麼後面的兩條語句 ...
  • 順序表 1.順序表定義:線性表的順序表示指的是用一組地址連續的存儲單元依次存儲線性表的數據元素。假設線性表的每個元素需占用L個 存儲單元,並以所占的第一個單元的存儲地址作為數據元素的存儲位置。則線性表中第i+1個數據元素的存儲位置LOC(ai+1)和第i個數據 元素的存儲位置LOC(ai)之間滿足下 ...
  • (一)一個指針引用字元串的小例子 把字元串a複製到字元串b (二)字元指針做函數參數 實參和形參都可以選擇字元數組名和字元指針變數,但存在區別:(1)編譯時為字元數組分配若幹存儲單元,以存放個元素的值,而對字元指針變數,只分配一個存儲單元(2)指針變數的值是可以改變的,而數組名代表一個固定的值(數組 ...
  • #115. 無源匯有上下界可行流 描述 這是一道模板題。 n n n 個點,m m m 條邊,每條邊 e e e 有一個流量下界 lower(e) \text{lower}(e) lower(e) 和流量上界 upper(e) \text{upper}(e) upper(e),求一種可行方案使得在所 ...
  • 重載的定義及特點 在同一個類中,允許存在一個以上的同名函數, 只要他們的參數個數或者參數類型不同(不僅指兩個重載方法的參數類型不同,還指相同參數擁有不同的參數類型順序)就構成重載。重載只和參數列表有關係,跟返回值類型無關,即返回值類型不能作為重載的條件。 ...
  • 前言 在去年的時候,在各種渠道中略微的瞭解了SpringBoot,在開發web項目的時候是如何的方便、快捷。但是當時並沒有認真的去學習下,畢竟感覺自己在Struts和SpringMVC都用得不太熟練。不過在看了很多關於SpringBoot的介紹之後,並沒有想象中的那麼難,於是開始準備學習Spring ...
  • Python 語音:與機器進行語音交流,讓機器明白你說什麼,這是人們長期以來夢寐以求的事情。 語音識別是一門交叉學科。近二十年來,語音識別技術取得顯著進步,開始從實驗室走向市場。人們預計,未來10年內,語音識別技術將進入工業、家電、通信、汽車電子、醫療、家庭服務、消費電子產品等各個領域。 語音識別... ...
  • Java在如今的發展趨勢而言,一直都是處於流行的原因自然也是隨之而存在的。 java的特點如下幾個方面: 1.簡單性 Java 實際上是一個 C++去掉了複雜性之後的簡化版。如果讀者沒有編程經驗,會發現 Java 並不難掌握, 而如果讀者有 C 語言或是 C++語言基礎,則會覺得 Java 更簡單, ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...