python---自定义字段验证
各个字段类,含正则和验证方法
#字段类 class IPField: REGULAR = "^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}" def __init__(self,error_dict=None,required=True): self.error_dict={} if error_dict: self.error_dict.update(error_dict) self.required=required self.error=None self.is_valid=False self.value=None def validate(self,name,input_value): if not self.required: #允许为空 if input_value.strip(): ret = re.match(IPField.REGULAR, input_value) if ret: self.is_valid = True self.value = ret.group() else: if self.error_dict.get('valid', None): self.error = self.error_dict['valid'] else: self.error = "%s is invalid" % name else: self.is_valid = True self.value=input_value else: #不允许为空 if not input_value.strip(): if self.error_dict.get('required',None): self.error=self.error_dict['required'] else: self.error="%s is required"%name else: ret = re.match(IPField.REGULAR,input_value) if ret: self.is_valid=True self.value=ret.group() else: if self.error_dict.get('valid',None): self.error=self.error_dict['valid'] else: self.error="%s is invalid"%name #可以含有多个文件名 class FileField: REGULAR = "^(\w\.pdf)|(\w\.mp3)|(\w\.py)$" def __init__(self,error_dict=None,required=True): self.error=None self.success_file_name_list={} self.value=None self.is_valid=True#后面只要有一个错误,就是错 self.required=required self.error_dict={} if error_dict: self.error_dict.update(error_dict) def validate(self,name,all_file_name_list):#all_file_name_list所有文件文件名 if not self.required: # if not input_value.strip(): # ret=re.match(FileField.REGULAR,input_value) # if ret: # self.is_valid=True # self.value=input_value # else: # if self.error_dict.get('valid',None): # self.error=self.error_dict['valid'] # else: # self.error="%s is invalid"%name # else: # self.is_valid=True # self.value=input_value if not all_file_name_list: self.is_valid=True else: #循环匹配所有 for input_value in all_file_name_list: ret = re.match(FileField.REGULAR, input_value) if ret: self.success_file_name_list.append(input_value) else: self.is_valid=False if self.error_dict.get('valid', None): self.error = self.error_dict['valid'] else: self.error = "%s is invalid" % name break else: if not all_file_name_list: self.is_valid=False if self.error_dict.get('required',None): self.error=self.error_dict['required'] else: self.error="%s is required"%name else: #循环匹配所有 for input_value in all_file_name_list: ret = re.match(FileField.REGULAR, input_value) if ret: self.success_file_name_list.append(input_value) else: self.is_valid=False if self.error_dict.get('valid', None): self.error = self.error_dict['valid'] else: self.error = "%s is invalid" % name break #字符串验证 class StringField: REGULAR = "(.*)" def __init__(self,error_dict=None,required=True): self.is_valid=False self.value=None self.error=None self.error_dict={} if error_dict: self.error_dict.update(error_dict) self.required=required def validate(self,name,input_value): if not self.required: #允许为空 if input_value.strip(): ret = re.match(StringField.REGULAR,input_value) if ret: self.is_valid=True self.value=input_value else: if self.error_dict.get('valid',None): self.error=self.error_dict['valid'] else: self.error="%s is invalid"%name else: self.is_valid=True self.value=input_value else:#不允许为空 if not input_value.strip(): if self.error_dict.get('required',None): self.error=self.error_dict['required'] else: self.error="%s is required"%name else: ret=re.match(StringField,input_value) if ret: self.is_valid=True self.value=input_value else: if self.error_dict.get('valid',None): self.error=self.error_dict['valid'] else: self.error="%s is invalid"%name #复选框验证 class CheckBoxField: def __init__(self,required=True,error_dict=None): self.is_valid=False self.error=None self.required=required if error_dict: self.error_dict=error_dict self.value=None def validate(self,name,input_value): #用户表单输入的数据可以为空 if not self.required: self.is_valid=True self.value=input_value else: if not input_value: if self.error_dict.get('required',None): self.error=self.error_dict['required'] else: self.error="%s is required"%name else: self.is_valid=True self.value=input_value
验证类基类
#form验证基类 class BaseForm(object): def check_valid(self,handler): flag=True error_message_dict={} success_dict={} for key,regular in self.__dict__.items(): #用户输入值 if type(regular) == CheckBoxField: input_val=handler.get_arguments(key) elif type(regular)==FileField: #包含上传多个文件[{'body':'','filename':''},{'body':'','filename':''}] file_list=handler.request.files.get(key) #获取其中的文件名 input_val=[] for item in file_list: input_val.append(item['filename']) else: input_val=handler.get_argument(key) regular.validate(key,input_val) if regular.is_valid: success_dict[key]=regular.value else: flag=False error_message_dict[key]=regular.error return flag,success_dict,error_message_dict
具体验证类子类:
#form验证类,采用对象 class HomeForm(BaseForm): def __init__(self): self.ip = IPField(required=True,error_dict={'required':'数据不为空',"valid":"验证出错"}) self.host=StringField(required=True,error_dict={'required':"主机名必须存在","valid":"这都会出错"}) self.sex=CheckBoxField(required=True,error_dict={'required':'复选框必须选择'}) # self.file=FileField(required=True,error_dict={'valid':'文件格式不正确'})
其他业务:
#采用HomeForm验证类 class HomeHandler(tornado.web.RequestHandler): def get(self): self.render('home.html',error_dict=None) def post(self, *args, **kwargs): formCk = HomeForm() is_valid,success_dict,error_dict=formCk.check_valid(self) if is_valid: print(success_dict) self.write("ok") else: print(error_dict) self.render('home.html',error_dict=error_dict)
settings={ 'static_path':'statics', 'template_path':'views', } application=tornado.web.Application([ (r"/index",IndexHandler), (r"/home",HomeHandler), ],**settings) if __name__ == "__main__": application.listen(8080) tornado.ioloop.IOLoop.instance().start()
前端代码:
<form method="post" action="/home"> <input type="text" placeholder="主机" name="host"/> <input type="text" placeholder="IP" name="ip"> <input type="checkbox" name="sex" value="1"/>男 <input type="checkbox" name="sex" value="2"/>女 <input type="file" name="file"> <input type="file" name="file"> <span> {% if error_dict and 'ip' in error_dict %} {{error_dict['ip']}} {% end %} {% if error_dict and 'host' in error_dict %} {{error_dict['host']}} {% end %} </span> <input type="submit" value="提交"/> </form>