装饰器:
装饰器定义:本质就是函数;功能是,为其他函数添加附加功能。(器:函数) #__iter__()与iter(x)功能一样
原则:1.不修改被修饰函数的源代码;2.不修改被修饰函数的调用方式
装饰器的知识储备:装饰器=高阶函数+函数嵌套+闭包(高阶函数定义:1.函数接收的参数是一个函数名;2.函数的返回值是一个参数名;3.满足上述条件任意之一,都可称之为高阶函数)(函数嵌套:函数内部再定义一个子函数)(闭包:在一个作用域里放入定义变量,相当于打了一个包。闭即封装变量,函数名也是一个变量)
# import time # def cal(l): # start_time=time.time() # res=0 # for i in l: # time.sleep(0.05) # res+=i # stop_time=time.time() #对原函数修饰时间,但是修改了源代码 # print('函数运行时间是%s' %(stop_time-start_time)) # return res # print(cal(range(100))) # import time # def foo(): # time.sleep(2) # print('你好啊雷师傅') # # def test(func): # print(func) # start_time=time.time() # func() # stop_time = time.time() #通过高阶函数接收参数名实现了修饰功能,但改变了调用方式 # print('函数运行的时间是%s' %(stop_time-start_time)) # test(foo) # #test函数是高阶,foo函数不是 # import time # def foo(): # time.sleep(3) # print("from the foo") # def timer(func): # start_time=time.time() # func() # stop_time = time.time() # 通过高阶函数返回值为参数名实现了修饰功能,调用方式也没变,但函数会多运行一次 # print('函数运行的时间是%s' %(stop_time-start_time)) # return func # foo = timer(foo) # foo() # def father(name): #函数嵌套与闭包 # print('from father %s' %name) # def son(): # name='lytt' # print('儿子是%s' %name) # def grandson(): # # name = 'lyttt' # print('孙子是%s' %name) # grandson() # print(locals()) #打印当前的全部局部标量 # son() # father('lyt') #一个嵌套的函数就相当于一个闭包,闭包封装变量,使用变量时先从自己里面找,没找到再往外找 # #装饰器的架子 # def timmer(func): # def wrapper(): # print(func) # func() # return wrapper # import time # def timmer(func): # def wrapper(): # print(func) # start_time=time.time() # func() # stop_time = time.time() # print('运行时间是%s' %(stop_time-start_time)) # return wrapper # def test(): # time.sleep(3) # print('test函数运行完毕') # test = timmer(test) #获取wrapper地址,这一步也不符合调用方式 # test() # #原函数无return的终极版本: # import time # def timmer(func): # def wrapper(): # # print(func) # start_time=time.time() # func() # stop_time = time.time() # print('运行时间是%s' %(stop_time-start_time)) # return wrapper # @timmer #@timmer相当于test = timmer(test) # def test(): # time.sleep(3) # print('test函数运行完毕') # test() # #原函数有return的终极版本: # import time # def timmer(func): # def wrapper(): # # print(func) # start_time=time.time() # res=func() # stop_time = time.time() # print('运行时间是%s' %(stop_time-start_time)) # return res # return wrapper # @timmer #@timmer相当于test = timmer(test) # def test(): # time.sleep(3) # print('test函数运行完毕') # return '这是test返回值' # res=test() # print(res) # #原函数有return且有参数的初级版本: # import time # def timmer(func): # def wrapper(name,age): # # print(func) # start_time=time.time() # res=func(name,age) # stop_time = time.time() # print('运行时间是%s' %(stop_time-start_time)) # return res # return wrapper # @timmer # def test(name,age): # time.sleep(3) # print('test函数运行完毕,名字是【%s】,年龄是【%s】' %(name,age)) # return '这是test返回值' # res=test('lyt',18) # print(res) # #原函数有return且有参数的终级版本: # import time # def timmer(func): # def wrapper(*args,**kwargs): # # print(func) # start_time=time.time() # res=func(*args,**kwargs) # stop_time = time.time() # print('运行时间是%s' %(stop_time-start_time)) # return res # return wrapper # @timmer # def test(name,age,gender): # time.sleep(3) # print('test函数运行完毕,名字是【%s】,年龄是【%s】性别是【%s】' %(name,age,gender)) # return '这是test返回值' # res=test('lyt',18,gender='male') # print(res)
解压序列:
# a,b,c=(1,2,3) #一个变量对应一个值 # print(a) # a,*_,c=[10,2,4,7,5,9,2,456,765,4,78] #取开头和结尾 # print(a,c) # a,*d,c=[10,2,4,7,5,9,2,456,765,4,78] #取中间值 # print(d) # a,b=[1,2] #ab值互换 # x=a # a=b # b=x # print(a,b) # f1 = 1 #ab值互换,更简单 # f2 = 2 # f1,f2 = f2,f1 # print(f1,f2)
函数闭包为函数加上认证功能
# uesr_dic = {'username':None,'login':False} # def auth_func(func): # def wrapper(*args,**kwargs): # if uesr_dic['username'] and uesr_dic['login']: # res = func(*args, **kwargs) # return res # username=input('用户名:').strip() # passwd=input('密码:').strip() # if username == 'lyt' and passwd == '123': # uesr_dic['username']=username #拿的全局变量的引用,改的也就是全局变量 # uesr_dic['login']=True # res=func(*args,**kwargs) # return res # else: # print('用户密码错误,请重新输入') # return wrapper(*args,**kwargs) # return wrapper # # def index(): # print('欢迎来到xx主页') # # @auth_func # def home(name): # print('%s,欢迎回家' %name) # # @auth_func # def shopping_car(name): # print('%s购物车里有[%s,%s,%s]' %(name,'奶茶','方便面','书')) # # index() # home('lyt') # shopping_car('lyt') #进阶版 # user_dic = [{'name':'ppp','passwd':'123'},{'name':'yyy','passwd':'123'},{'name':'zzz','passwd':'123'},{'name':'mmm','passwd':'123'},{'name':'lyt','passwd':'123'}]#可以用open方式打开文件里的列表 # current_dic = {'username':None,'login':False} # def auth(auth_type): # def auth_func(func): # def wrapper(*args,**kwargs): # if auth_type=='filedb': # print('验证方式是filedb') # if current_dic['username'] and current_dic['login']: # res = func(*args, **kwargs) # return res # username=input('用户名:').strip() # passwd=input('密码:').strip() # for user_list in user_dic: # if username == user_list['name'] and passwd == user_list['passwd']: # current_dic['username']=username # current_dic['login']=True # res=func(*args,**kwargs) # return res # else: # print('用户密码错误,请重新输入') # return wrapper(*args,**kwargs) # elif auth_type=='ssss': # print('以ssss方式认证') # elif auth_type=='dddd': # print('以dddd方式运行') # return wrapper # return auth_func # # @auth(auth_type='filedb') ##执行了两次,得到wrapper地址 # def index(): # print('欢迎来到xx主页') # # @auth(auth_type='ssss') # def home(name): # print('%s,欢迎回家' %name) # # @auth(auth_type='filedb') # def shopping_car(name): # print('%s购物车里有[%s,%s,%s]' %(name,'奶茶','方便面','书')) # # index() # home('lyt') # shopping_car('lyt')
一个规范:python文件只写不会运行的功能,要测试运行在(if __name__=='__main__')下进行
三级菜单初识:
#三级菜单: # while True: #分步退出 # print('level1') # a=input('level1>>:') # if a=='quit':break # while True: # print('level2') # a = input('level2>>:') # if a == 'quit': break # while True: # print('level3') # a = input('level3>>:') # if a == 'quit': break # tag=True #可实现一步就结束 # while tag: # print('level1') # a=input('level1>>:') # if a=='quit':break # if a=='quit out':tag=False # while tag: # print('level2') # a = input('level2>>:') # if a == 'quit': break # if a == 'quit out': tag = False # while tag: # print('level3') # a = input('level3>>:') # if a == 'quit': break # if a == 'quit out': tag = False
查询功能:
#__name__ == __main__ 相当于一个变量 def fetch(data): print('\033[1:43m这是查询功能\033[0m') print('\033[1:43m用户数据是\033[0m',data) backend_data='backend %s' %data with open('haproxy.conf','r')as read_f: tag=False ret=[] for read_line in read_f: if read_line.strip() == backend_data: tag=True continue if tag: if read_line.startswith('backend'): break print('\033[1:43m%s\033[0m' %read_line,end='') ret.append(read_line) return ret def add(): pass import os def change(data): print('这是修改功能') print('用户输入的数据是',data) data=eval(data) data[0] #文件当中的一条记录 data_backend='backend ' + data[0]['backend'] old_server_recond='%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[0]['recond']['server'],data[0]['recond']['server'],data[0]['recond']['weight'],data[0]['recond']['maxconn']) new_server_recond='%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[1]['recond']['server'],data[1]['recond']['server'],data[1]['recond']['weight'],data[1]['recond']['maxconn']) print('用户想要修改的数据是%s' %old_server_recond) res=fetch(data[0]['backend']) # print('来自change函数-->>',res) if not res or old_server_recond not in res: return '你要修改的数据不存在' else: index=res.index(old_server_recond) #找到old_server_recond的索引位置 # print(index) res[index]=new_server_recond print(res) res.insert(0,'%s\n' %data_backend) with open('haproxy.conf','r') as read_f,open('haproxy.conf_new','w') as write_f: tag=False has_write=False for read_line in read_f: # print(read_line.strip()) if read_line.strip() ==data_backend: tag=True continue if tag and read_line.startswith('backend'): tag=False if not tag: write_f.write(read_line) else: if not has_write: for record in res: write_f.write(record) has_write=True os.rename('haproxy.conf','haproxy.conf.bak') os.rename('haproxy.conf_new','haproxy.conf') os.remove('haproxy.conf.bak') #更改文件就是新文件复制并改名 def delete(): pass if __name__=='__main__': msg=''' 1:查询 2:添加 3:修改 4:删除 5:退出 ''' msg_dic={ '1':fetch, '2':add, '3':change, '4':delete, } while True: print(msg) choice=input('请输入你的选项').strip() #去两边空格回车,不能去中间的! if not choice:continue if choice=='5':break data=input("请输入你的数据:") res=msg_dic[choice](data) print(res) #要修改为的数据[{'backend':'www.oldboy1.org','recond':{'server':'100.1000.7.9','weight':'20','maxconn':'30'}},{'backend':'www.oldboy1.org','recond':{'server':'105.1000.7.9','weight':'20','maxconn':'300'}}]
程序解耦:
def file_handler(backend_data,res=None,type='fetch'): if type == 'fetch': with open('haproxy.conf','r')as read_f: tag=False ret=[] for read_line in read_f: if read_line.strip() == backend_data: tag=True continue if tag: if read_line.startswith('backend'): break print('\033[1:43m%s\033[0m' %read_line,end='') ret.append(read_line) return ret elif type == 'change': with open('haproxy.conf', 'r') as read_f, open('haproxy.conf_new', 'w') as write_f: tag = False has_write = False for read_line in read_f: # print(read_line.strip()) if read_line.strip() == backend_data: tag = True continue if tag and read_line.startswith('backend'): tag = False if not tag: write_f.write(read_line) else: if not has_write: for record in res: write_f.write(record) has_write = True def fetch(data): print('\033[1:43m这是查询功能\033[0m') print('\033[1:43m用户数据是\033[0m',data) backend_data='backend %s' %data ret = file_handler(backend_data) return ret def add(): pass import os def change(data): print('这是修改功能') print('用户输入的数据是',data) data=eval(data) data[0] #文件当中的一条记录 backend_data='backend ' + data[0]['backend'] old_server_recond='%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[0]['recond']['server'],data[0]['recond']['server'],data[0]['recond']['weight'],data[0]['recond']['maxconn']) new_server_recond='%sserver %s %s weight %s maxconn %s\n' %(' '*8,data[1]['recond']['server'],data[1]['recond']['server'],data[1]['recond']['weight'],data[1]['recond']['maxconn']) print('用户想要修改的数据是%s' %old_server_recond) res=fetch(data[0]['backend']) # print('来自change函数-->>',res) if not res or old_server_recond not in res: return '你要修改的数据不存在' else: index=res.index(old_server_recond) #找到old_server_recond的索引位置 # print(index) res[index]=new_server_recond print(res) res.insert(0,'%s\n' %backend_data) file_handler(backend_data,res=res,type='change') os.rename('haproxy.conf','haproxy.conf.bak') os.rename('haproxy.conf_new','haproxy.conf') os.remove('haproxy.conf.bak') #更改文件就是新文件复制并改名 def delete(): pass if __name__=='__main__': msg=''' 1:查询 2:添加 3:修改 4:删除 5:退出 ''' msg_dic={ '1':fetch, '2':add, '3':change, '4':delete, } while True: print(msg) choice=input('请输入你的选项').strip() #去两边空格回车,不能去中间的! if not choice:continue if choice=='5':break data=input("请输入你的数据:") res=msg_dic[choice](data) print(res)
浙公网安备 33010602011771号