python単純フォーム検証フレームワークの実装

35714 ワード

 
  
# encoding=utf-8

from app.models import Student

from flask import g



import re

from flask.ext.wtf import Form

from wtforms import StringField, RadioField, PasswordField, TextAreaField, BooleanField, DateField, ValidationError, \

    IntegerField

from wtforms.validators import DataRequired, Length, Regexp, Email, EqualTo

from wtforms.widgets import ListWidget, HTMLString





class BSListWidget(ListWidget):

    def __call__(self, field, **kwargs):

        kwargs.setdefault('id', field.id)

        html = ""

        for subfield in field:

            html += u'<label class="radio-inline"> %s%s </label>' % (subfield(), subfield.label.text)

        return HTMLString(html)





class Fields(object):

    notnull = u'        '



    def get_len_str(min=None, max=None):

        if min and not max:

            return u"            %d" % min

        elif max and not min:

            return u"            %d" % max

        else:

            return u'          %d,  %d' % (min, max)



    username = StringField(label=u'        ',

                           validators=[DataRequired(message=notnull),

                                       Length(min=0, max=15, message=get_len_str(0, 16)),

                                       ])



    password = PasswordField(label=u'     ', description=u'     ',

                             validators=[DataRequired(message=notnull),

                                         Length(min=0, max=60, message=get_len_str(min=0, max=61)),

                                         ])

    confirm_password = PasswordField(label=u'     ',

                                     description=u'     ',



                                     validators=[DataRequired(message=notnull),

                                                 Length(min=5, max=60, message=get_len_str(min=4, max=61)),

                                                 EqualTo(u'confirm_password', message=u'          '), ]

                                     )

    student_amount = StringField(label=u'           ',

                                 validators=[Regexp(re.compile(r"\d"))])



    is_active = RadioField(label=u'      ',

                           coerce=int,

                           choices=[(0, u' '), (1, u' ')],

                           default=0,

                           widget=BSListWidget())



    notice = TextAreaField(label=u'         ')



    attachment = StringField(label=u'    ',

                             validators=[Length(min=0, max=32, message=get_len_str(min=0, max=33))], )



    is_comment_teacher = RadioField(label=u'       ',

                                    coerce=int,

                                    choices=[(0, u' '), (1, u' ')],

                                    default=0,

                                    widget=BSListWidget())



    student_name = StringField(label=u'       ',

                               description='',

                               validators=[DataRequired(message=notnull),

                                           Length(min=0, max=15, message=get_len_str(0, 16)),

                                           ])



    sex = RadioField(label=u'    ',

                     coerce=int,

                     choices=[(0, u' '), (1, u' ')],

                     default=0,

                     widget=BSListWidget())



    user_type = RadioField(label=u'  ',

                           coerce=str,

                           choices=[(u'student', u'  '), (u'teacher', u'  '), (u'admin', u'   ')],

                           default=u'student',

                           widget=BSListWidget())



    mark = StringField(label=u'    ',

                       default=0,

                       validators=[DataRequired(message=notnull),

                                   Length(min=0, max=100, message=get_len_str(0, 101)),

                                   ])

    comment = TextAreaField(label=u'          ',

                            validators=[

                                Length(min=0, max=128, message=get_len_str(0, 129)),

                            ])



    title = StringField(label=u'          ',

                        validators=[

                            Length(min=0, max=128, message=get_len_str(0, 129)),

                        ])

    description = TextAreaField(label=u'          ')



    task_start_date = DateField(label=u'    ')

    task_end_date = DateField(label=u'    ')



    comment_start_date = DateField(label=u'    ')

    comment_end_date = DateField(label=u'    ')





class LoginForm(Form):

    username = Fields.username

    password = Fields.password



    user_type = Fields.user_type



    remember_me = BooleanField(label=u'   ', default=u'y')



    errors = {}





    def validate_fields(self):

        status = True

        status = status and self.username.validate(self)

        status = status and self.username.validate(self)

        self.password.validate()



        # def validate(self):

        self._fields

        self.validate_on_submit()

        return self.username.validate(self)



        # def validate_username(self, field):

        # user = Student.get_user(field.data)

        # if not user:

        # print 'not user'

        # self.errors['username'] = u'      '

        # raise ValidationError(message=u'        ')

        # else:

        # print 'user'

        # return True



        #

        # def validate_password(self,field):

        # if g.user:

        # if field.data != g.user.username:

        # field.errors.append(message=u'       ')

        # return False

        #

        # def validate_user_type(self, field):

        # print field.data

        #

        # def validate_remember_me(self,field):

        # if field.data:

        # print field.data





class StuInfo(Form):

    username = Fields.username

    student_name = Fields.student_name

    sex = Fields.sex

    attachment = Fields.attachment

    mark = Fields.mark

    comment = Fields.comment





class BaseForm(object):

    def __init__(self, form):

        self.username = Field(label=u'   ', type='text', validators={'min_length': 5})



        for field_name, data in form.items():

            getattr(self, field_name).data = data



    def validate(self):

        status = True

        for field_name in self.__dict__:

            status = status and getattr(self, field_name).validate()

        return status





class Field(object):

    def __init__(self, label=None, type='text', validators={}, description=None, data=''):

        self.data = data

        self.label = label

        self.type = type

        self.validators = validators

        self.description = description



    def validate(self):

        status = True

        for method_name, param in self.validators.items():

            print method_name, param

            status = status and getattr(self, method_name)(param)

        return status



    def is_null(self, status):

        if status:

            return True

        if not self.data:

            return False

        if hasattr(self.data, 'replace') and len(self.data.replace(' ', '')) > 0:

            return False

        if len(self.data) == 0:

            return False

        return True



    def min_length(self, min=-1):

        if not self.is_null(False) and len(self.data) < min:

            return False

        return True



    def max_length(self, max):

        if not self.is_null(False) and len(self.data) > max:

            return False

        return True



    def min(self, min):

        try:

            if int(self.data) < min:

                return False

            return True

        except Exception, e:

            print e

            return False



    def max(self, max):

        try:

            if int(self.data) > max:

                return False

            return True

        except Exception, e:

            print e

            return False



    def equal_to(self, data):

        if self.data != data:

            return False

        return True



    def select_from(self, *args):

        if self.data not in args:

            return False

        return True





if __name__ == '__main__':

    b = BaseForm({'username': 'o'})

    print b.validate()

    print 'ok'