[关闭]
@bergus 2016-04-11T15:35:01.000000Z 字数 4152 阅读 1830

flask 后台表单验证模块

python flask 表单验证


我不想直接用flask的wtf模块,太大,功能太多,用不了。但后台也不能不做验证吧,我比较懒,不想一行一行写代码验证,所以就写了一个验证模块,对于小项目也够用了

  1. # encoding=utf-8
  2. # 这是一个简单的后台验证框架,因为前台的话要用ajax处理,那么后台就不需要复杂的表单处理了
  3. # 基础表单类,具体验证表单继承它
  4. from flask import session
  5. class BaseForm(object):
  6. def __init__(self,form=None):
  7. self.form = form
  8. self.fields = []
  9. self.errors = [] # 错误信息存放的地方
  10. self.init()
  11. def init(self):
  12. if not self.form:
  13. return False
  14. # 给表单赋值
  15. for field_name in dir(self):
  16. field = self.__getattribute__(field_name)
  17. if isinstance(field,Field):
  18. if field_name in self.form:
  19. field.data = self.form[field_name]
  20. self.fields.append((field_name,field.validate))
  21. # 验证自定义的以validate_开头的方法
  22. for validate_method in dir(self):
  23. if validate_method.startswith('validate_'):
  24. self.fields.append((validate_method,self.__getattribute__(validate_method)))
  25. # 验证入口
  26. def validate(self):
  27. status = True
  28. for field_name,validate_method in self.fields:
  29. status = validate_method() and status
  30. if not status:
  31. print field_name,status
  32. return False
  33. return status
  34. # 字段类,主要提供字段的各种验证和约束
  35. class Field(object):
  36. def __init__(self,label=None,type='text',validators={},description=None,data=''):
  37. self.data = data
  38. self.label = label
  39. self.type = type
  40. self.validators = validators
  41. self.description = description
  42. # 验证入口,验证该字段所有的约束条件
  43. def validate(self):
  44. status = True
  45. for method_name,param in self.validators.items():
  46. status = self.__getattribute__(method_name)(param) and status
  47. if not status:
  48. print method_name,status
  49. return True
  50. return status
  51. # 验证数据是否复合正则表达式
  52. def __rule(self,re_str):
  53. import re
  54. pattern = re.compile(re_str)
  55. match = pattern.match(self.data)
  56. if match:
  57. return True
  58. return False
  59. # 对开提供的正则表达式模块
  60. def regex(self,re_str):
  61. return self.__rule(re_str)
  62. # 是否为数字
  63. def digits(self,status=True):
  64. return self.__rule(r"\d+")
  65. # 是否是链接
  66. def url(self,status=True):
  67. re_str = r"^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$"
  68. return self.__rule(re_str)
  69. # 是否是邮箱
  70. def email(self,status=True):
  71. re_str = r"^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$"
  72. return self.__rule(re_str)
  73. # 是否为空
  74. def not_null(self,status):
  75. if not status:
  76. return True
  77. if not self.data:
  78. return False
  79. if hasattr(self.data,'replace') and len(self.data.replace(' ','')) < 0:
  80. return False
  81. if len(self.data) == 0:
  82. return False
  83. return True
  84. # 最小长度
  85. def min_length(self,min=-1):
  86. return self.not_null(True) and len(self.data) >= min
  87. # 长度范围
  88. def length_range(self,range=[]):
  89. if self.not_null(True) and len(range) == 2:
  90. data_length = len(self.data)
  91. return data_length >= range[0] and data_length <= range[1]
  92. return False
  93. # 最大长度
  94. def max_length(self,max):
  95. return self.not_null(True) and len(self.data) <= max
  96. # 最小值
  97. def min(self,min):
  98. try:
  99. return int(self.data) >= min
  100. except Exception,e:
  101. print e
  102. return False
  103. # 最大值
  104. def max(self,max):
  105. try:
  106. return int(self.data) <= max
  107. except Exception,e:
  108. print e
  109. return False
  110. # 值范围
  111. def data_range(self,range=[]):
  112. try:
  113. data = int(self.data)
  114. if len(range) == 2:
  115. return data >= range[0] and data <= range[1]
  116. return False
  117. except Exception,e:
  118. print e
  119. return False
  120. # 是否等于field
  121. def equal_to(self,field):
  122. return self.data == field.data
  123. # 是否为规定的值
  124. def choices(self,args=[]):
  125. return self.data in args
  126. # 检查多选框
  127. def checked(self,status=True):
  128. if not status:
  129. return True
  130. return self.data in [1,'y','yes','true']
  131. if __name__ == '__main__':
  132. class Test(BaseForm):
  133. name = Field()
  134. password = Field()
  135. email = Field()
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注