• Flask ==> wtform使用和源码解析


    Flask ==>   wtform

    1.安装:

    pip3 install wtforms

    2.用户登录

    目录结构:

    1.app.py

    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 MyValidator(object):
        def __init__(self,message):
            self.message = message
        def __call__(self, form, field):
            print(field.data)
            if field.data == '章鱼哥':
                return None
            raise validators.StopValidation(self.message)
    
    
    class LoginForm(Form):
        name = simple.StringField(
            label='用户名',
            validators=[
                # MyValidator(message='用户名必须等于章鱼哥')  #自定义
                validators.DataRequired(message='用户名不能为空.'),
                validators.Length(min=6, max=18, message='用户名长度必须大于%(min)d且小于%(max)d')
            ],
            widget=widgets.TextInput(), #页面上生成input 标签
            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-zd$@$!%*?&]{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)
    
    
    
    
    
    # ########################### 用户注册 ##########################
    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

    2.login.html

    <!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.html

    3.register.html

    <!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

    Flask ==>   wtform源码解析

    app.py:

    1.代码从上到下,一定先走Loginform类,先解释这个类,这个类里面的静态其实已经实例化了。

    2.默认的 metaclass 等于type,怎么自定义? 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
    
    class Foo(metaclass = MyType):
        def __init__(self,name):
            self.name = name

    方式二:

    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
    
    
    class Foo(Mytype("MyType",(object,),{})):   #类似于 metaclass
        def __init__(self,name):
            self.name = name

    优化方式二: 指定了 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

    3.1.进入继承Form类,查看。

    class Form(with_metaclass(FormMeta, BaseForm)):

    ps:  with_metaclass 跳入

    def with_metaclass(meta, base=object):
        # meta = FormMeta("NewBase", (BaseForm,), {})
        # base = BaseForm
        return meta("NewBase", (base,), {})   #实例化了 meta 类

    ps:  相当于给Form类定义metaclass,也就是说:这个类刚创建的时候,先执行metaclass,执行它的__init__方法。

    小结: 

    对于一个类来说:

      首先: 1. 先执行type的 __init__ 方法。

          2. 实例化时,执行type的__call__ 方法,

          3. 由 type的__call__方法调用类的__new__方法,

          4.最后,在执行 类的__init__ 方法。

         5.实例化完成。

    1. creation_counter = 2 排序   (通过这个计数,来排顺序)

    2.静态字段被修改了,下次访问就是改了的值

    切入点:

    1.当定义好一个自定义的Form类,项目加载Form类所在模块,代码都做了什么?

    2.在视图函数中实例化Form类,代码都了什么?

      - 模板渲染调用Form的字段时,代码都做了什么?

    3.前端填好数据,返回后端校验时,代码做了什么?

     

    详细分析:

    1.项目加载Form类所在模块

      Form类:

        这是声明Form的代码: class Form(with_metaclass(FormMeta, BaseForm))

        可见这里调用一个函数  with_metaclass  跳入:

    1 def with_metaclass(meta, base=object):
    2      return meta("NewBase", (base,), {})
    View Code

        该函数返回了一个FormMeta元类创建的NewBase类作为Form类的基类

        元类创建类会执行元类的__init__方法

    1  def __init__(cls, name, bases, attrs):
    2      type.__init__(cls, name, bases, attrs)
    3      cls._unbound_fields = None
    4      cls. = None
    View Code
    • 此处为Form类定义了_unbound_fields和_wtforms_meta两个静态字段

      类的字段:

    • 拿一个字段举例:username = simple.StringField()
    • 可见是实例化了一个StringField类
      • StringField类定义了一个静态字段:widget = widgets.TextInput()
        • 这里是实例化了一个插件类TextInput
          • TextInput类定义了一个静态字段:input_type = 'text'指定生成html标签时的type
          • 基类中的__init__方法只是将检测了一下input_type
      • StringField类没有__init__方法,__new__方法,显然要从基类中寻找
        • 基类中的__new__方法返回的是:UnboundField(cls, *args, **kwargs)实例化了一个UnboundField类的对象

      UnboudField 跳入:

    class UnboundField(object):
        _formfield = True
        creation_counter = 0
    
        def __init__(self, field_class, *args, **kwargs):
            UnboundField.creation_counter += 1
            self.field_class = field_class
            self.args = args
            self.kwargs = kwargs
            self.creation_counter = UnboundField.creation_counter
    • 可见UnboundField类封装了字段的类StringField,并给了字段一个编号,看来wtforms应该就是通过这个编号来识别字段的顺序
      • 基类中的__init__方法

        • 有意思的是此时__init__的接收的self已经不是Field类的实例,而是UnboundField类的实例
        • init这里大部分操作都是常规的赋值操作,不过也有个值得关注的地方
          • if _translations is not None: self._translations = _translations
            • 通过这两行代码可以看出,wtforms内部还实现了实现了多语言的提示信息
    • 最后得出结论,form类的静态字段如username此时存储的是UnboundField类的实例

    2.在视图函数中实例化form类

      - 首先执行元类的__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:  #cls 表示  loginform 那个类
                fields = []
                for name in dir(cls):   #dir  拿到loginform类的所有字段
                    if not name.startswith('_'):
                        unbound_field = getattr(cls, name)
                        if hasattr(unbound_field, '_formfield'):
                            fields.append((name, unbound_field))
                # 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]))
                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__:   # cls.__mro__继承所有的类
                    if 'Meta' in mro_class.__dict__:
                        bases.append(mro_class.Meta)
                cls._wtforms_meta = type('Meta', tuple(bases), {})
            return type.__call__(cls, *args, **kwargs)
    • 这里就是给form类的_unbound_fields和_wtforms_meta赋值
      • 使用dir(cls)获取form类的所有变量字符串,当其不为'_'开头时说明是自定义form的字段,获取字段的对应的对象,根据字段的编号排序后加入_unbound_fields列表
        • 此处的判断做的还不够好,或许通过cls.__dict__.items()获取到所有的变量名和值,判断值是否为UnboundField的实例,若为UnboundField的实例则加入列表
      • 使用__mro__获取form类所有的继承关系,挨个寻找这些类中的Meta字段对应的类计入bases列表,最后通过type一次型创建一个继承了所有bases列表中的类的Meta类,并存入_wtforms_meta字段
    • 接着应该执行类的__new__方法,不过这里没有定义,忽略此步骤

    • 然后执行类的__init__方法

        def __init__(self, formdata=None, obj=None, prefix='', data=None, meta=None, **kwargs):
            meta_obj = self._wtforms_meta() #self._wtforms_meta = type('Meta', tuple(bases), {})
            if meta is not None and isinstance(meta, dict):
                meta_obj.update_values(meta)    #如果有值就更新进去。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)
    • 这里首先实例化了_wtforms_meta字段对应的Meta类然后传入了基类的__init__方法

     def __init__(self, fields, prefix='', meta=DefaultMeta()):
            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)
                field = meta.bind_field(self, unbound_field, options)
                self._fields[name] = field
      • prefix是设置生成html标签的name属性的值的前缀
      • meta是一个继承了form类以及所有form类继承的类中的Meta类的实例
        • 这里检测了是否启用了csrf字段
        • 并将meta中额外定义的有关csrf的字段加入extra_fields
      • 最后将fields和extra_fields中所有的字段全部放置在form类实例的_fields字段中
        • 这里通过field = meta.bind_field(self, unbound_field, options)对所有的UnboundField类实例做了处理,找回了原有的Field
    • 然后将类中的_fields表中的字段设置为form类实例的属性

      • 注意:此时的字段已经变回了原来的Field,尚不明确为何要多进行这样的操作
    • 这行代码主要是针对有数据传入时的操作self.process(formdata, obj, data=data, **kwargs)

      • 在第4点详细查看

    3.模板渲染调用form的字段

    • 此时本质上就是调用了字段的__str__方法,把返回的字符串放置在模板

        def __str__(self):
            """
            Returns a HTML representation of the field. For more powerful rendering,
            see the `__call__` method.
            """
            return self()  #调用自己的__call__ 方法
    View Code
    • 转为调用字段的__call__方法

     def __call__(self, **kwargs):
     2      """
     3      Render this field as HTML, using keyword args as additional attributes.
     4 
     5      This delegates rendering to
     6      :meth:`meta.render_field <wtforms.meta.DefaultMeta.render_field>`
     7      whose default behavior is to call the field's widget, passing any
     8      keyword arguments from this call along to the widget.
     9 
    10      In all of the WTForms HTML widgets, keyword arguments are turned to
    11      HTML attributes, though in theory a widget is free to do anything it
    12      wants with the supplied keyword arguments, and widgets don't have to
    13      even do anything related to HTML.
    14      """
    15      return self.meta.render_field(self, kwargs)
    View Code
    • 继续调用Meta类的render_field方法,这个方法在DefaultMeta类

     1 def render_field(self, field, render_kw):
     2      """
     3      render_field allows customization of how widget rendering is done.
     4 
     5      The default implementation calls ``field.widget(field, **render_kw)``
     6      """
     7      other_kw = getattr(field, 'render_kw', None)
     8      if other_kw is not None:
     9          render_kw = dict(other_kw, **render_kw)
    10      return field.widget(field, **render_kw)
    • 这里调用了字段的插件对象的__call__方法

    1 def __call__(self, field, **kwargs):
    2      kwargs.setdefault('id', field.id)
    3      kwargs.setdefault('type', self.input_type)
    4      if 'value' not in kwargs:
    5          kwargs['value'] = field._value()
    6      return HTMLString('<input %s>' % self.html_params(name=field.name, **kwargs))
    View Code
    • 至此,完成了Form类实例的__str__方法,返回了一个HTML的input标签的字符串

    4.前端调好数据,返回后端校验

    1. 前端填好数据,返回后端校验
      • 依然是实例化一个Form类的对象,大部分流程和第2点讨论的一致,不过在执行到Form类的__init__方法的最后一行时开始不同

        • self.process(formdata, obj, data=data, **kwargs)

     1 def process(self, formdata=None, obj=None, data=None, **kwargs):
     2      formdata = self.meta.wrap_formdata(self, formdata)
     3  
     4      if data is not None:
     5          kwargs = dict(data, **kwargs)
     6  
     7      for name, field, in iteritems(self._fields):
     8          if obj is not None and hasattr(obj, name):
     9              field.process(formdata, getattr(obj, name))
    10          elif name in kwargs:
    11              field.process(formdata, kwargs[name])
    12          else:
    13              field.process(formdata)
    View Code
    • 这里根据传入的数据不同做不同的操作

      • formdata = self.meta.wrap_formdata(self, formdata)是将不具有getlist方法的formdata的对象封装一个getlist对象
      • field.process函数就是将数据封装进self.data和self.row_data 
     1 def process(self, formdata, data=unset_value):
     2      self.process_errors = []
     3      if data is unset_value:
     4          try:
     5              data = self.default()
     6          except TypeError:
     7              data = self.default
     8  
     9      self.object_data = data
    10  
    11      try:
    12          self.process_data(data)
    13      except ValueError as e:
    14          self.process_errors.append(e.args[0])
    15  
    16      if formdata:
    17          try:
    18              if self.name in formdata:
    19                  self.raw_data = formdata.getlist(self.name)
    20              else:
    21                  self.raw_data = []
    22              self.process_formdata(self.raw_data)
    23          except ValueError as e:
    24              self.process_errors.append(e.args[0])
    25  
    26      try:
    27          for filter in self.filters:
    28              self.data = filter(self.data)
    29      except ValueError as e:
    30              self.process_errors.append(e.args[0])
    View Code
    • 然后调用form.validate方法

    1 def validate(self):
    2      extra = {}
    3      for name in self._fields:
    4          inline = getattr(self.__class__, 'validate_%s' % name, None)
    5          if inline is not None:
    6              extra[name] = [inline]
    7      return super(Form, self).validate(extra)
    View Code
      • 把每个字段的校验规则封装进extra
    • 然后调用BaseForm的validate()

    def validate(self, extra_validators=None):
     2      self._errors = None
     3      success = True
     4      for name, field in iteritems(self._fields):
     5          if extra_validators is not None and name in extra_validators:
     6              extra = extra_validators[name]
     7          else:
     8              extra = tuple()
     9          if not field.validate(self, extra):
    10              success = False
    11      return success
    View Code
    • 然后挨个调用字段的校验方法完成校验

  • 相关阅读:
    DOM event beforeload
    有关点击付费的十大失误-转载
    DOM 事件DOMContentLoaded
    Git 系列之四:Git 进阶功能转载
    Qt webkit中单独编译JavaScriptCore
    搜索知识与技巧集锦转载
    webkit中DOM 事件有多少
    Git 系列之三:Windows 下 Git 配置与使用指南转载
    简历:第一章:技术亮点如何写
    实战:第十三章:工作中熬夜加班学到的
  • 原文地址:https://www.cnblogs.com/zhongbokun/p/8254678.html
Copyright © 2020-2023  润新知