Form 表单提交

会有一股神秘感。 提交于 2020-01-01 11:54:04
简单方法(1)
#!/usr/bin/env python
# -*- coding:utf-8 -*-

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 chec_inpu(self,handler):
        exits = True
        inp_dict = {}
        for key,value in self.__dict__.items():
            user_input = handler.get_argument(key)
            res = re.match(value,user_input)
            if not res:
                exits = False
            inp_dict[key] = user_input
        return exits,inp_dict

class MainHandler(tornado.web.RequestHandler):
    def get(self):

        self.render('index.html')
    def post(self, *args, **kwargs):
        obj = MainForm()
        ret,inp_dict = obj.chec_inpu(self)
        print(ret,inp_dict)
        self.render('index.html')

settings = {
    # 模版路劲配置
    'template_path':'views',
    # 静态路劲配置 如css 和 js
    'static_path':'static',
    #静态文件的前缀
    'static_url_prefix':'/ssss/',

}
# 路由映射
application = tornado.web.Application([
    (r"/index", MainHandler),
] , **settings)


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

  

高级版()

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web
import re

class ReHandler(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 rehande(self,ret):

        re_dict = {
            'host': "(.*)",
            'ip':"^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$",
            'port':"(\d+)",
            'phone':"^1[3|4|5|8][0-9]\d{8}$",
        }

        return  re_dict[ret]
# 匹配验证
class ReForm(ReHandler):

    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
        # True可以为空  默认不能为空
        self.is_valid = False
        # 用户value
        self.value = None

    # 验证
    def validate(self,name,input_value):
        if not self.required:
            print(input_value)
            print('123')
            self.value = input_value
            self.is_valid = True
        else:
            # ru
            if not input_value.strip():
                if self.error_dict.get('required',None):
                    self.error = self.error_dict.get('required')
                else:
                    self.error = '%s is required'%name
            else:
                rets = self.rehande(name)

                ret = re.match(rets,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.get('valid')
                    else:
                          self.error = '%s is valid'%name

#需要验证的input required等于True必须填写
class HomeHandler(object):
    def __init__(self):
        self.ip = ReForm(required=True,error_dict={'required':'空的不要','valid':'格式错误'})
        self.phone = ReForm(required=True,error_dict={'required':'空的不要','valid':'格式错误'})
        self.host = ReForm(required=False)
        self.port = ReForm(required=False)

class FildHandler(HomeHandler):

    def chec_inpu(self,handler):
        exxxx = True
        success_dict_value = {}
        error_dict_value = {}

        for  home_key,home_value in  self.__dict__.items():
            user_value = handler.get_argument(home_key,None)
            home_value.validate(home_key,user_value)
            if home_value.is_valid:
                success_dict_value[home_key] = home_value.value
            else:
                error_dict_value[home_key] = home_value.error
                exxxx = False
        return exxxx , success_dict_value ,error_dict_value
class MainHandler(tornado.web.RequestHandler):
    def get(self):

        self.render('index.html',errors={})
    def post(self, *args, **kwargs):
        obj = FildHandler()
        exxxx_obj , success_obj ,error_obj = obj.chec_inpu(self)
        if exxxx_obj:
            self.write('成功')
            print(success_obj)
        else:
            self.render('index.html',errors = error_obj)

settings = {
    # 模版路劲配置
    'template_path':'views',
    # 静态路劲配置 如css 和 js
    'static_path':'static',
    #静态文件的前缀
    'static_url_prefix':'/ssss/',

}
# 路由映射
application = tornado.web.Application([
    (r"/index", MainHandler),
] , **settings)


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

  

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post" action="/index">
        <input type="text" placeholder="host" name="host">{{ errors.get('host',"")}}
        <input type="text" placeholder="ip" name="ip">{{ errors.get('ip',"")}}
        <input type="text" placeholder="port" name="port">{{ errors.get('port',"")}}
        <input type="text" placeholder="phone" name="phone">{{ errors.get('phone',"")}}
        <input type="submit" placeholder="提交">
    </form>
</body>
</html>

  

文件提交

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import tornado.ioloop
import tornado.web
import re
# 封装错误指令 和正则匹配
class ReHandler(object):
    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
        # True可以为空  默认不能为空
        self.is_valid = False
        # 用户value
        self.value = None
    def rehande(self,ret):
        re_dict = {
            'host': "(.*)",
            'ip':"^(25[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3}$",
            'port':"(\d+)",
            'phone':"^1[3|4|5|8][0-9]\d{8}$",
            'fileinfo':"^(\w+\.pdf)|(\w+\.mp3)|(\w+\.py)$",
        }
        return  re_dict[ret]

# 普通input匹配验证
class ReForm(ReHandler):
    def validate(self,name,input_value):
        if self.required:
            # 如果用户输入是空的
            if not input_value.strip():
                if self.error_dict.get('required',None):
                    self.error = self.error_dict.get('required')
                else:
                    self.error = '%s is required'%name
            # 如果不是空的
            else:
                rets = self.rehande(name)
                ret = re.match(rets,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.get('valid')
                    else:
                          self.error = '%s is valid'%name
        else:
            self.value = input_value
            self.is_valid = True

# 文件匹配验证
class FileForm(ReHandler):
    def filedata(self,re_file,file_name,file_info):
        if self.required:
            ret_neme = self.rehande(re_file)
            ret = re.match(ret_neme,file_name)
                # 判断文件名 是否正确
            if ret:
                self.is_valid = True
                with open(file_name,'wb') as e:
                   e.write(file_info)
                   e.close()
            else:
                  self.is_valid = False
                  if self.error_dict.get('valid',None):
                      self.error = self.error_dict.get('valid')
                  else:
                      self.error = ' 文件的格式错误了'

        else:
            # 如果上传判断 文件格式
            if file_name.strip():
                ret_neme = self.rehande(re_file)
                ret = re.match(ret_neme,file_name)
                if ret:
                    self.is_valid = True
                    with open(file_name,'wb') as e:
                       e.write(file_info)
                       e.close()
                else:
                    if self.error_dict.get('valid',None):
                        self.error = self.error_dict.get('valid',None)
                    else:
                        self.error = '文件格式错误'
            # 如果没有上传默True
            else:
                self.value = file_info
                self.is_valid = True

#需要验证的 类型 等于True必须填写
class HomeHandler(object):
    def __init__(self):
        self.ip = ReForm(required=True,error_dict={'required':'空的不要','valid':'格式错误'})
        self.phone = ReForm(required=True,error_dict={'required':'空的不要','valid':'格式错误'})
        self.host = ReForm(required=False)
        self.port = ReForm(required=False)
        self.fileinfo = FileForm(required=True,error_dict={'required':'空的不要','valid':'格式错误'})

class FildHandler(HomeHandler):
    def chec_inpu(self,handler):
        exxxx = True
        success_dict_value = {}
        error_dict_value = {}
        for  home_key,home_value in  self.__dict__.items():
            # input类型
            if type(home_value) == ReForm:
                user_value = handler.get_argument(home_key,None)
                home_value.validate(home_key,user_value)
                if home_value.is_valid:
                    success_dict_value[home_key] = home_value.value
                else:
                    error_dict_value[home_key] = home_value.error
                    exxxx = False
            # file类型
            elif type(home_value) == FileForm:
                user_file = handler.request.files.get(home_key,[])
                print(len(user_file))
                for i in user_file:
                    file_name = i['filename']
                    file_body = i['body']
                    home_value.filedata(home_key,file_name,file_body)
                    if home_value.is_valid:
                        success_dict_value[file_name] = file_body
                    else:
                        error_dict_value[home_key] =  home_value.error


        return exxxx , success_dict_value ,error_dict_value

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.render('index.html',errors={})
    def post(self, *args, **kwargs):

        obj = FildHandler()
        exxxx_obj , success_obj ,error_obj = obj.chec_inpu(self)
        if exxxx_obj:
            self.write('成功')
            print(success_obj)
        else:
            print(error_obj)
            self.render('index.html',errors = error_obj)

settings = {
    # 模版路劲配置
    'template_path':'views',
    # 静态路劲配置 如css 和 js
    'static_path':'static',
    #静态文件的前缀
    'static_url_prefix':'/ssss/',

}
# 路由映射
application = tornado.web.Application([
    (r"/index", MainHandler),
] , **settings)


if __name__ == "__main__":
    application.listen(8888)
    tornado.ioloop.IOLoop.instance().start()

  

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <form method="post" action="/index" enctype="multipart/form-data">

        <input type="text" placeholder="host" name="host">{{ errors.get('host',"")}}
        <input type="text" placeholder="ip" name="ip">{{ errors.get('ip',"")}}
        <input type="text" placeholder="port" name="port">{{ errors.get('port',"")}}
        <input type="text" placeholder="phone" name="phone">{{ errors.get('phone',"")}}
        <p>
        <input type="file" name="fileinfo"/>
            {{ errors.get('fileinfo',"")}}
        
        </p>
        <input type="submit" placeholder="提交">
    </form>
</body>
</html>

  

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!