#!/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

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAcUAAABsCAIAAACUxz5BAAAFfUlEQVR4nO3bT27jVBzA8XcTjsFyjsARWHKEOcJcIEr6N0or0c4MB2DJcjaVWLIqRYAYBIIRINiGRSVj/Of52fklnmY+H0XIcZ6fnyPrW5dCegAgQpp7AQBHQk8BYugpQAw9BYihpwAx9BQgRnr9+gsvLy8vr91faQtABD0FiKGnADH0FCCGngLE0FOAGHoKEENPAWJ09/QVvHp14HuRHd3f3798+fLzOdze3t7f38/9Bcyvt6cH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8OHjK4kpKaZ4I4av5RZx/1GFu3XC5/6Pe4yMeN6m2lMSZzeJ/lcjl2wcdHT+lW+PeoXQZMSEb56VL2+XTChPn9mZHTPipe43+Wy+X389HTrZ7Sxz3w5CwWi+/ms1gs5v4C5qendHMPPDmLxeJhPnq61VP6uAeenOVy+e18/L6/zfQUDnwvsqO7u7vVarWYw3K5vLu7m/sLmF/wHwQAPlh6ChBDTwFi6ClADD0FiKGnADH0FCCGngLE0FOAGHoKEENPAWLoKUAMPQWIoacAMfQUIIaeAsTQU4AYegoQQ08BYugpQAw9BYihpwAx9BQghp4CxNBTgBh6ChBDTwFi6ClADD0FiKGnADH0FCCGngLE0FOAGHoKEENPAWLoKUAMPQWIoacAMfQUIIaeAsTQU4AYegoQQ08BYugpQAw9BYihpwAx9BQghp4CxNBTgBh6ChBDTwFi6ClADD0FiKGnADH0FCCGngLE0FOAGHoKEENPAWLoKUAMPQWIoacAMfQUIIaeAsTQU4AYegoQQ08BYugpQAw9BYihpwAx9BQgxr+ihu/JtFrcNgAAAABJRU5ErkJggg==" alt="" />

#!/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

最新文章

  1. IIS错误:在唯一密钥属性 fileExtension=&quot;.url&quot;时,无法添加类型为“mimeMap”的重复集合项
  2. Android笔记之——线程
  3. 建立时间和保持时间(setup time 和 hold time)
  4. DeepLearning之路(三)MLP
  5. 在C/C++程序里打印调用栈信息
  6. Ch2.Making Reconmmendation in PCI
  7. Docker搭建MySQL服务
  8. linux极点五笔无法输入词组_ibus设置
  9. C++ Primer笔记整理
  10. ConfigurationManager.GetSection()方法的使用
  11. python 函数简介之三
  12. Maven快速搭建GUI项目
  13. bootstrap datepicker 属性设置 以及方法和事件
  14. RBAC权限模型——项目实战(转)
  15. Python3 isdigit()方法
  16. Spring Cloud 2-Zuul 网关服务(六)
  17. Hive篇--相关概念和使用二
  18. excel2013 打开为灰色空白 左下角显示就绪 要把文件拖进去才能打开!
  19. Springboot Session集群处理
  20. 《Android高级进阶》读书笔记

热门文章

  1. 利用AOP写2PC框架(二)
  2. int[] convert byte[]
  3. PKU 1005
  4. C#中ref,out
  5. 使用UltraISO制作U盘启动盘——转载
  6. python动态获取对象的属性和方法 (转载)
  7. MySQL 约束的讲解
  8. Gradle – Spring 4 MVC Hello World Example
  9. 在win下面使用cdt+cygwin+cmake
  10. 为什么我们不喜欢用富UI控件
  11. Android 学习笔记之实时保存数据-现场保护onSaveInstanceState()
  12. 强化学习(十)Double DQN (DDQN)
  13. iBinary C++STL模板库关联容器之map/multimap
  14. klearn.preprocessing.PolynomialFeatures学习
  15. &lt;a&gt; 标签详解
  16. php memcache 基础操作
  17. zstu 4247-萌新的旅行
  18. 单元测试(四)-隔离框架NSubstitute
  19. vue单页面应用项目优化总结(转载)
  20. invalid self-signed ssl certificate