#!/usr/bin/env python
# -*- coding:utf- -*-
import tornado.ioloop
import tornado.web
import re
class MainForm(object):
def __init__(self):
self.host = "(.*)"
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}$"
self.port = '(\d+)'
self.phone = '^1[3|4|5|8][0-9]\d{8}$' def check_valid(self,handle):
flag = True
value_dict = {}
for key,regular in self.__dict__.items():
input_value = handle.get_argument(key)
val = re.match(regular, input_value)
print(key, input_value, val, regular)
if not val:
flag = False
value_dict[key] = input_value
return flag, value_dict class IndexHandler(tornado.web.RequestHandler):
def get(self, *args, **kwargs):
self.render('index.html') def post(self, *args, **kwargs):
obj = MainForm() is_valid, value_dict = obj.check_valid(self)
print(is_valid) if is_valid:
print(value_dict) settings = {
'template_path': 'views',
'static_path': 'statics',
# 'static_url_prefix':'/statics/',
# 'xsrf_cookies':True
} application = tornado.web.Application([
(r"/index", IndexHandler),
# (r"/checkout", CheckoutHandler), ], **settings) if __name__ == "__main__":
application.listen()
tornado.ioloop.IOLoop.instance().start()
优化前form.py
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/index" method="post">
<input type="text" name="host" placeholder="host" >
<input type="text" name="ip" placeholder="ip" >
<input type="text" name="port" placeholder="port" >
<input type="text" name="phone" placeholder="phone" >
<input type="submit" value="提交">
</form>
</body>
</html>
index.html
#!/usr/bin/env python
# -*- coding:utf- -*-
#!/usr/bin/env python
# -*- coding:utf- -*-
import tornado.ioloop
import tornado.web
import re class IPFiled:#定义类
#定义正则
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, required=True, error_dict=None):
# required = True, error_dict = {'required': "别闹,别整空的..", "valid": "骚年,格式错误了"}
"""
required = True的话证明不能为空,
:param error_dict: 存错误的字典信息
"""
# 封装了错误信息
self.error_dict = {}#定义一个新的错误字典{'required': "别闹,别整空的..", "valid": "骚年,格式错误了"}
if error_dict:#如果错误字典有内容,为True
self.error_dict.update(error_dict)#那就把错误内容更新到字典里面 self.required = required #默认等于true self.error = None # 错误信息
self.value = None#值
self.is_valid = False#验证是否通过,默认为false def validate(self, name, input_value): #定义name和输入的值(name是key也是ip)
"""
:param name: 字段名
:param input_value: 用户表单中输入的内容
:return:
"""
if not self.required: #如果为false,那么就是不用输入
# 用户输入可以为空
self.is_valid = True #通过验证
self.value = input_value#值是输入的值
else:#如果为True
if not input_value.strip():#假如输入为空值的话,not inp..strip就是True,就是证明没有值
if self.error_dict.get('required',None): #如果错误列表获取
# error_dict = {'required': "别闹,别整空的..", "valid": "骚年,格式错误了"}
self.error = self.error_dict['required']#"别闹,别整空的..
else:#如果没有别闹,别整空的,就是required的值为空的话
self.error = "%s is required" % name #self.error = 这个”ip is ....“
else:#假如有值
ret = re.match(IPFiled.REGULAR, input_value)#(正则, 输入的信息)
if ret:#如果有匹配的话
self.is_valid = True #
self.value = input_value #输入的内容,value
else:#没有匹配到的话
if self.error_dict.get('valid', None): # 获取valid的值有内容的话,valid": "骚年,格式错误了"
self.error = self.error_dict['valid']#那么错误的值就等于这个
else:#如果没有则为无效的(这句的意思就是如果你没人输入骚年什么的。。。就这句了)
self.error = "%s is invalid" % name class BaseForm: #定义baseform类
def check_valid(self, handle):#handle就是homehandler的对象
flag = True#定义了一个标志位
error_message_dict = {} #错误消息列表
success_value_dict = {}#成功消息列表
for key, regular in self.__dict__.items():#{}
# key: ip .....
# handle: HomeIndex对象,self.get_... self.
# regular: IPFiled(required=True)
input_value = handle.get_argument(key)#输入ip的值
# input_value = 用户输入的值
# 将具体的验证,放在IPFiled对象中
regular.validate(key, input_value) #regular是HomeForm类里面的IPFiled。。。,所以可以调用IPFiled的validate方法
if regular.is_valid:
success_value_dict[key] = regular.value#key等于输入的值
else:
error_message_dict[key] = regular.error#等于错误信息
flag = False return flag, success_value_dict, error_message_dict class HomeForm(BaseForm):
def __init__(self):
self.ip = IPFiled(required=True, error_dict={'required': "别闹,别整空的..", "valid": "骚年,格式错误了"})
#self.ip就是一个对象
class HomeHandler(tornado.web.RequestHandler):
def get(self):
self.render('home.html',error_dict = None) def post(self, *args, **kwargs):
obj = HomeForm()#创建了对象
# 获取用户输入的内容
# 和正则表达式匹配
is_valid, success_dict, error_dict = obj.check_valid(self)
if is_valid:
print('success',success_dict)
else:
print('error', error_dict)
self.render('home.html', error_dict = error_dict) settings = {
'template_path': 'views',
'static_path': 'statics',
'static_url_prefix': '/statics/',
} application = tornado.web.Application([
# (r"/index", IndexHandler),
(r"/home", HomeHandler),
], **settings) if __name__ == "__main__":
application.listen()
tornado.ioloop.IOLoop.instance().start()
注释版ip表单验证
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/home" method="post">
<input type="text" name="ip" placeholder="ip">
{% if error_dict %}
<span> {{ error_dict['ip']}}</span>
{% end %}
<input type="submit"> </form>
</body>
</html>
home.html