本文主要是介绍Flask---wtforms源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
我在Flask—wtforms使用博文中简单的学习了下wtforms的简单使用,这篇博客就专门来了解下wtforms
的源码流程
我们在使用Form
时候,我们会构造如下的实例对象
class LoginForm(Form):user = simple.StringField(validators=[validators.DataRequired(message='用户名不能为空.'),# validators.Length(min=6, max=18, message='用户名长度必须大于%(min)d且小于%(max)d')],widget=widgets.TextInput(),render_kw={'class': 'form-control'})
那我们分析源码就从LoginForm
的继承类Form
来进行分析
class Form(with_metaclass(FormMeta, BaseForm)):
def with_metaclass(meta, base=object):return meta("NewBase", (base,), {})
说明Form类是通过元类进行构造,FormMeta是type元类,BaseForm是From类继承的父类
我们看下FormMeta
元类的初始化__init__
方法
def __init__(cls, name, bases, attrs):type.__init__(cls, name, bases, attrs)cls._unbound_fields = Nonecls._wtforms_meta = None
当在FormMeta初始化方法时候,通过cls.XX操作,会去触发该类的__setattr__
方法
def __setattr__(cls, name, value):"""Add an attribute to the class, clearing `_unbound_fields` if needed."""if name == 'Meta':cls._wtforms_meta = Noneelif not name.startswith('_') and hasattr(value, '_formfield'):cls._unbound_fields = Nonetype.__setattr__(cls, name, value)
然后我们回过头继续看LoginForm
class LoginForm(Form):user = simple.StringField(validators=[validators.DataRequired(message='用户名不能为空.'),# validators.Length(min=6, max=18, message='用户名长度必须大于%(min)d且小于%(max)d')],widget=widgets.TextInput(),render_kw={'class': 'form-control'})
我们看下LoginForm
类中的user
属性,在构造实例时候, 会先调用__new__
,然后执行__init__
方法,我们先来看Field
的__new__
方法
def __new__(cls, *args, **kwargs):if '_form' in kwargs and '_name' in kwargs:return super(Field, cls).__new__(cls)else:return UnboundField(cls, *args, **kwargs)
继而跟踪UnboundField
代码
def __init__(self, field_class, *args, **kwargs):UnboundField.creation_counter += 1self.field_class = field_classself.args = argsself.kwargs = kwargsself.creation_counter = UnboundField.creation_counter
通过UnboundField.creation_counter += 1统计UnboundField的实例对象个数
然后回过头来看Field
的__init__
方法,看看初始化做了什么操作?
for v in itertools.chain(self.validators, [self.widget]):flags = getattr(v, 'field_flags', ())for f in flags:setattr(self.flags, f, True)
通过itertools.chain
连接validators
和 [self.widget]
,设置一些默认的校验规则,例如
required
和hidden
等等
至此下面的代码中我们完成了一些列的初始化操作
class LoginForm(Form):user = simple.StringField(validators=[Myvalidators(message="用户名必须是safly"), # 也可以自定义正则validators.DataRequired(message='用户名不能为空.'),# validators.Length(min=6, max=18, message='用户名长度必须大于%(min)d且小于%(max)d')],widget=widgets.TextInput(),render_kw={'class': 'form-control'})
最后生成的数据格式如下:
LoginForm._unbound_fields = None
LoginForm._wtforms_meta = None
LoginForm.name = UnboundField(simple.StringField, *args, **kwargs,creation_counter=1)
我们在使用如下的类似代码,来使用wtforms
if request.method == 'GET':form = LoginForm()return render_template('login.html',form=form)
所以我们接下来分析LoginForm()
的实例化的过程
当在实例化时候,会先调用元类的init,然后是元类的call方法,然后在调用LoginForm的父类系列方法,然后是自己的系列方法,那我们先看下class FormMeta(type)
元类的__call__
方法
def __call__(cls, *args, **kwargs):if cls._unbound_fields is None:fields = []for name in dir(cls):if not name.startswith('_'):unbound_field = getattr(cls, name)if hasattr(unbound_field, '_formfield'):fields.append((name, unbound_field))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__:if 'Meta' in mro_class.__dict__:bases.append(mro_class.Meta)cls._wtforms_meta = type('Meta', tuple(bases), {})return type.__call__(cls, *args, **kwargs)
在__call__
方法中,获取我们代码LoginForm
类中的含有_formfield
属性的Field
实例,最后 cls._unbound_fields = fields
进行赋值操作
然后for mro_class in cls.__mro__
,
以下是cls.__mro__
列表
mroclass <class '__main__.LoginForm'>
mroclass <class 'wtforms.form.Form'>
mroclass <class 'wtforms.compat.NewBase'>
mroclass <class 'wtforms.form.BaseForm'>
mroclass <class 'object'>
我们最终在class Form(with_metaclass(FormMeta, BaseForm)):
类中找到了Meta
Meta = DefaultMeta
最后通过元类构造cls._wtforms_meta = type('Meta', tuple(bases), {})
通过上述的操作,我们看下数据状态
LoginForm._unbound_fields = [('name',UnboundField(simple.StringField, *args, **kwargs,creation_counter=1),),('pwd',UnboundField(simple.PasswordField, *args, **kwargs,creation_counter=2),),]LoginForm._wtforms_meta = class Meta(DefaultMeta):passLoginForm.name = UnboundField(simple.StringField, *args, **kwargs,creation_counter=1)
最后在继续看class Form(with_metaclass(FormMeta, BaseForm))
类,当执行完元类的__init__、__call__
方法之后,就会去执行Form类的__init__
方法,
def __init__(self, formdata=None, obj=None, prefix='', data=None, meta=None, **kwargs):meta_obj = self._wtforms_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)
通过super(Form, self).__init__(self._unbound_fields, meta=meta_obj, prefix=prefix)
可以看出它继承了父类的BaseForm
的__init__
方法
def __init__(self, fields, prefix='', meta=DefaultMeta()):if prefix and prefix[-1] not in '-_;:/.':prefix += '-'self.meta = metaself._prefix = prefixself._errors = Noneself._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
此时的数据格式如下:
LoginForm对象._fields = {'name': simple.StringField() }
LoginForm对象.name = simple.StringField()
然后执行Form类中的__init__
方法
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)
def process(self, formdata=None, obj=None, data=None, **kwargs):formdata = self.meta.wrap_formdata(self, formdata)if data is not None:# XXX we want to eventually process 'data' as a new entity.# Temporarily, this can simply be merged with kwargs.kwargs = dict(data, **kwargs)for name, field, in iteritems(self._fields):if obj is not None and hasattr(obj, name):field.process(formdata, getattr(obj, name))elif name in kwargs:field.process(formdata, kwargs[name])else:field.process(formdata)
以上就是LoginForm()
的执行流程
我们知道wtforms
最终是渲染到页面上,我们就来看下print(form.name)
做了什么操作把?
它会执行Field
类的__str__
方法
def __str__(self):return self()
调用对象自身,继而调用该对象的__call__
方法
def __call__(self, **kwargs):return self.meta.render_field(self, kwargs)
def render_field(self, field, render_kw):other_kw = getattr(field, 'render_kw', None)if other_kw is not None:render_kw = dict(other_kw, **render_kw)return field.widget(field, **render_kw)
继而调用field.widget
的__call__
方法
def __call__(self, field, **kwargs):kwargs.setdefault('id', field.id)kwargs.setdefault('type', self.input_type)if 'value' not in kwargs:kwargs['value'] = field._value()return HTMLString('<input %s>' % self.html_params(name=field.name, **kwargs))
我们最后看看是如何进行校验操作的吧?
def validate(self):"""Validates the form by calling `validate` on each field, passing anyextra `Form.validate_<fieldname>` validators to the field validator."""extra = {}for name in self._fields:inline = getattr(self.__class__, 'validate_%s' % name, None)if inline is not None:extra[name] = [inline]return super(Form, self).validate(extra)
我们在进行字段校验时候,会书写如下的代码:
def validate_name(self, field):"""自定义pwd_confirm字段规则,例:与pwd字段是否一致:param field::return:"""# 最开始初始化时,self.data中已经有所有的值print(field.data) # 当前name传过来的值# print(self.data) # 当前传过来的所有的值:name,gender.....obj = SQLHelper.fetch_one('select id from user where user =%s',[field.data,])if obj:raise validators.ValidationError("用户名已经存在") # 继续后续验证
最后调用父类的方法进行验证
def validate(self, extra_validators=None):self._errors = Nonesuccess = Truefor name, field in iteritems(self._fields):if extra_validators is not None and name in extra_validators:extra = extra_validators[name]else:extra = tuple()if not field.validate(self, extra):success = Falsereturn success
以上wtforms的源码流程
这篇关于Flask---wtforms源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!