[关闭]
@bergus 2015-12-02T14:33:04.000000Z 字数 5118 阅读 1699

python表单校验摘录

python flask wtf


  1. # encoding=utf-8
  2. from app.models import Student
  3. from flask import g
  4. import re
  5. from flask.ext.wtf import Form
  6. from wtforms import StringField, RadioField, PasswordField, TextAreaField, BooleanField, DateField, ValidationError, \
  7. IntegerField
  8. from wtforms.validators import DataRequired, Length, Regexp, Email, EqualTo
  9. from wtforms.widgets import ListWidget, HTMLString
  10. class BSListWidget(ListWidget):
  11. def __call__(self, field, **kwargs):
  12. kwargs.setdefault('id', field.id)
  13. html = ""
  14. for subfield in field:
  15. html += u'<label class="radio-inline"> %s%s </label>' % (subfield(), subfield.label.text)
  16. return HTMLString(html)
  17. class Fields(object):
  18. notnull = u'该项输入不能为空'
  19. def get_len_str(min=None, max=None):
  20. if min and not max:
  21. return u"该项输入的最小长度必须是%d" % min
  22. elif max and not min:
  23. return u"该项输入的最大长度必须是%d" % max
  24. else:
  25. return u'该输入的长度必须大于%d,小于%d' % (min, max)
  26. username = StringField(label=u'请输入您的用户名',
  27. validators=[DataRequired(message=notnull),
  28. Length(min=0, max=15, message=get_len_str(0, 16)),
  29. ])
  30. password = PasswordField(label=u'请输入密码', description=u'请输入密码',
  31. validators=[DataRequired(message=notnull),
  32. Length(min=0, max=60, message=get_len_str(min=0, max=61)),
  33. ])
  34. confirm_password = PasswordField(label=u'请确认密码',
  35. description=u'请确认密码',
  36. validators=[DataRequired(message=notnull),
  37. Length(min=5, max=60, message=get_len_str(min=4, max=61)),
  38. EqualTo(u'confirm_password', message=u'两次输入的密码不一致'), ]
  39. )
  40. student_amount = StringField(label=u'请输入您指导的学生数量',
  41. validators=[Regexp(re.compile(r"\d"))])
  42. is_active = RadioField(label=u'是否激活账户',
  43. coerce=int,
  44. choices=[(0, u'否'), (1, u'是')],
  45. default=0,
  46. widget=BSListWidget())
  47. notice = TextAreaField(label=u'请填写对学生的通知')
  48. attachment = StringField(label=u'添加附加',
  49. validators=[Length(min=0, max=32, message=get_len_str(min=0, max=33))], )
  50. is_comment_teacher = RadioField(label=u'是否有评价功能',
  51. coerce=int,
  52. choices=[(0, u'否'), (1, u'是')],
  53. default=0,
  54. widget=BSListWidget())
  55. student_name = StringField(label=u'请输入您的姓名',
  56. description='',
  57. validators=[DataRequired(message=notnull),
  58. Length(min=0, max=15, message=get_len_str(0, 16)),
  59. ])
  60. sex = RadioField(label=u'您的性别',
  61. coerce=int,
  62. choices=[(0, u'男'), (1, u'女')],
  63. default=0,
  64. widget=BSListWidget())
  65. user_type = RadioField(label=u'您是',
  66. coerce=str,
  67. choices=[(u'student', u'学生'), (u'teacher', u'老师'), (u'admin', u'管理员')],
  68. default=u'student',
  69. widget=BSListWidget())
  70. mark = StringField(label=u'您的分数',
  71. default=0,
  72. validators=[DataRequired(message=notnull),
  73. Length(min=0, max=100, message=get_len_str(0, 101)),
  74. ])
  75. comment = TextAreaField(label=u'请填写您对学生的评语',
  76. validators=[
  77. Length(min=0, max=128, message=get_len_str(0, 129)),
  78. ])
  79. title = StringField(label=u'请填写毕业设计的题目',
  80. validators=[
  81. Length(min=0, max=128, message=get_len_str(0, 129)),
  82. ])
  83. description = TextAreaField(label=u'请填写毕业设计的描述')
  84. task_start_date = DateField(label=u'开始时间')
  85. task_end_date = DateField(label=u'结束时间')
  86. comment_start_date = DateField(label=u'开始时间')
  87. comment_end_date = DateField(label=u'结束时间')
  88. class LoginForm(Form):
  89. username = Fields.username
  90. password = Fields.password
  91. user_type = Fields.user_type
  92. remember_me = BooleanField(label=u'记住我', default=u'y')
  93. errors = {}
  94. def validate_fields(self):
  95. status = True
  96. status = status and self.username.validate(self)
  97. status = status and self.username.validate(self)
  98. self.password.validate()
  99. # def validate(self):
  100. self._fields
  101. self.validate_on_submit()
  102. return self.username.validate(self)
  103. # def validate_username(self, field):
  104. # user = Student.get_user(field.data)
  105. # if not user:
  106. # print 'not user'
  107. # self.errors['username'] = u'用户名不存在'
  108. # raise ValidationError(message=u'该用户名已被注册')
  109. # else:
  110. # print 'user'
  111. # return True
  112. #
  113. # def validate_password(self,field):
  114. # if g.user:
  115. # if field.data != g.user.username:
  116. # field.errors.append(message=u'用户密码不正确')
  117. # return False
  118. #
  119. # def validate_user_type(self, field):
  120. # print field.data
  121. #
  122. # def validate_remember_me(self,field):
  123. # if field.data:
  124. # print field.data
  125. class StuInfo(Form):
  126. username = Fields.username
  127. student_name = Fields.student_name
  128. sex = Fields.sex
  129. attachment = Fields.attachment
  130. mark = Fields.mark
  131. comment = Fields.comment
  132. class BaseForm(object):
  133. def __init__(self, form):
  134. self.username = Field(label=u'用户名', type='text', validators={'min_length': 5})
  135. for field_name, data in form.items():
  136. getattr(self, field_name).data = data
  137. def validate(self):
  138. status = True
  139. for field_name in self.__dict__:
  140. status = status and getattr(self, field_name).validate()
  141. return status
  142. class Field(object):
  143. def __init__(self, label=None, type='text', validators={}, description=None, data=''):
  144. self.data = data
  145. self.label = label
  146. self.type = type
  147. self.validators = validators
  148. self.description = description
  149. def validate(self):
  150. status = True
  151. for method_name, param in self.validators.items():
  152. print method_name, param
  153. status = status and getattr(self, method_name)(param)
  154. return status
  155. def is_null(self, status):
  156. if status:
  157. return True
  158. if not self.data:
  159. return False
  160. if hasattr(self.data, 'replace') and len(self.data.replace(' ', '')) > 0:
  161. return False
  162. if len(self.data) == 0:
  163. return False
  164. return True
  165. def min_length(self, min=-1):
  166. if not self.is_null(False) and len(self.data) < min:
  167. return False
  168. return True
  169. def max_length(self, max):
  170. if not self.is_null(False) and len(self.data) > max:
  171. return False
  172. return True
  173. def min(self, min):
  174. try:
  175. if int(self.data) < min:
  176. return False
  177. return True
  178. except Exception, e:
  179. print e
  180. return False
  181. def max(self, max):
  182. try:
  183. if int(self.data) > max:
  184. return False
  185. return True
  186. except Exception, e:
  187. print e
  188. return False
  189. def equal_to(self, data):
  190. if self.data != data:
  191. return False
  192. return True
  193. def select_from(self, *args):
  194. if self.data not in args:
  195. return False
  196. return True
  197. if __name__ == '__main__':
  198. b = BaseForm({'username': 'o'})
  199. print b.validate()
  200. print 'ok'
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注