自定义form验证
示例1:用户在前端输入内容,后端程序进行正则表达式处理,验证输入的内容是否符合格式要求。
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import tornado.ioloop 4 import tornado.web 5 6 class BaseForm(): 7 def check_valid(self, handle): 8 # 获取用户输入的内容 9 # 和正则表达式对比 10 flag = True 11 value_dict = {} 12 for key, regular in self.__dict__.items(): 13 input_value = handle.get_argument(key) 14 import re 15 ret = re.match(regular, input_value) 16 if not ret: 17 flag = False 18 value_dict[key] = input_value 19 return flag, value_dict 20 21 22 23 class CheckForm(BaseForm): 24 25 def __init__(self): 26 self.host = "(.*)" 27 self.ip = "^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$" 28 self.port = "(\d+)" 29 30 31 class LoginHandler(tornado.web.RequestHandler): 32 def get(self): 33 self.render('login.html') 34 35 def post(self, *args, **kwargs): 36 # 获取用户输入的内容 37 # 和正则表达式对比 38 obj = CheckForm() 39 is_valid, value_dict = obj.check_valid(self) 40 print(is_valid) 41 if is_valid: 42 print(value_dict) 43 44 45 46 47 48 settings = { 49 'template_path': 'views', #视图模板路径 50 'static_path': 'static', #静态文件路径 51 } 52 #路由映射,路由系统 53 def make_app(): 54 return tornado.web.Application([ 55 (r"/login", LoginHandler), 56 ], **settings) 57 58 if __name__ == "__main__": 59 app = make_app() 60 app.listen(8888) 61 tornado.ioloop.IOLoop.current().start()
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form method="post" action="/login"> 9 host:<input type="text" name="host" /> 10 ip:<input type="text" name="ip"/> 11 port:<input type="text" name="port"/> 12 <input type="submit" value="登录"/> 13 </form> 14 15 </body> 16 </html>
结果图示:
示例二:后端程序对用户输入的内容进行验证处理,并将验证的结果反馈到前端页面。
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 import tornado.ioloop 4 import tornado.web 5 import re 6 7 class IPFiled: 8 REGULAR = "^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$" 9 10 def __init__(self, error_dict=None, required=True): 11 self.error_dict = {}#封装了错误信息 12 if error_dict: 13 self.error_dict.update(error_dict) 14 self.required = required 15 self.error = None 16 self.is_valid = False 17 self.value = None 18 19 def validate(self, name, input_value): 20 """ 21 22 :param name: 字段名 23 :param input_value: 表单中用户输入的内容 24 :return: 25 """ 26 if not self.required: 27 #用户输入可为空 28 self.is_valid = True 29 self.value = input_value 30 else: 31 if not input_value.strip(): 32 if self.error_dict.get('required', None): 33 self.error = self.error_dict['required'] 34 else: 35 self.error = "%s is required" % name 36 else: 37 ret = re.match(IPFiled.REGULAR, input_value) 38 if ret: 39 self.id_valid = True 40 self.value = input_value 41 else: 42 if self.error_dict.get('valid', None): 43 self.error = self.error_dict['valid'] 44 else: 45 self.error = "%s is invalid" % name 46 47 class BaseForm(): 48 def check_valid(self, handle): 49 # 获取用户输入的内容 50 # 和正则表达式对比 51 flag = True 52 error_message_dict = {} 53 success_value_dict = {} 54 for key, regular in self.__dict__.items(): 55 input_value = handle.get_argument(key)#用户输入的内容 56 regular.validate(key, input_value)#将具体的验证,放在IPFiled了对象中 57 if regular.is_valid: 58 success_value_dict[key] = regular.value 59 else: 60 error_message_dict[key] = regular.error 61 flag = False 62 return flag, success_value_dict, error_message_dict 63 64 class CheckForm(BaseForm): 65 66 def __init__(self): 67 # self.ip = "^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$" 68 self.ip = IPFiled(required=True, error_dict={'required': "不能为空", 'valid': "格式错误了"}) 69 70 class HomeHandler(tornado.web.RequestHandler): 71 def get(self): 72 self.render('home.html', error_dict=None) 73 74 def post(self, *args, **kwargs): 75 # 获取用户输入的内容 76 # 和正则表达式对比 77 obj = CheckForm() 78 is_valid, success_dict, error_dict = obj.check_valid(self) 79 print(is_valid) 80 if is_valid: 81 print('success', success_dict) 82 else: 83 print('error', error_dict) 84 self.render('home.html', error_dict=error_dict) 85 86 87 88 89 90 settings = { 91 'template_path': 'views', #视图模板路径 92 'static_path': 'static', #静态文件路径 93 } 94 #路由映射,路由系统 95 def make_app(): 96 return tornado.web.Application([ 97 (r"/home", HomeHandler), 98 ], **settings) 99 100 if __name__ == "__main__": 101 app = make_app() 102 app.listen(8888) 103 tornado.ioloop.IOLoop.current().start()
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 </head> 7 <body> 8 <form method="post" action="/home"> 9 ip:<input type="text" name="ip"/> 10 {% if error_dict %} 11 <span style="color: red">{{error_dict['ip']}}</span> 12 {% end %} 13 <input type="submit" value="登录"/> 14 </form> 15 16 </body> 17 </html>
结果图示: