#装饰器 = 高阶函数+ 函数嵌套+ 函数闭包
#一、高阶函数:1.函数的调用值是函数;2.函数的返回值也是函数
import time
# def bar():
# time.sleep(1)
# print('from bar')
# def timer(func):
# start_time = time.time()
# func()
# stop_time = time.time()
# print('函数运行时间是%s' %(stop_time-start_time))
# return func
# bar = timer(bar)
# bar()
#上述实现方式的问题在于,会多运行一次bar()
#二、函数嵌套+函数闭包
# def timer(func):
# def wrapper():
# start_time = time.time()
# func()
# stop_time = time.time()
# print('函数运行时间是%s' %(stop_time-start_time))
# return wrapper
# @timer #在函数前面加'@timer', 相当于对函数进行装饰操作:bar = timer(bar)
# def bar():
# time.sleep(1)
# print('from bar')
# # bar = timer(bar)
# bar()
#三、函数闭包+返回值+参数
# def timer(func):
# def wrapper(*args,**kwargs):
# start_time = time.time()
# res = func(*args,**kwargs)
# stop_time = time.time()
# print('函数运行时间是%s' %(stop_time-start_time))
# return res
# return wrapper
# @timer #在函数前面加'@timer', 相当于对函数进行装饰操作:bar = timer(bar)
# def bar(name,age,gender):
# time.sleep(1)
# print('from bar,name is %s,age is %s,gender is %s' %(name,age,gender))
# return 'return from bar'
# # bar = timer(bar)
# res = bar('alex',18,'男')
# print(res)
#四、解压序列
# l = [1,2,3,4,621,3324,11,254,885,123,'aa','11221',2222]
# a,*_,b = l
# print(a,b)
# c = 1
# d = 2
# c,d = d,c
# print(c,d)
#给函数加认证
user_list =[
{'name':'alex','passwd':'1234'},
{'name':'keith','passwd':'12345'},
{'name':'mick','passwd':'1222'},
{'name':'june','passwd':'11111'},
{'name':'haha','passwd':'2345'}
]
user_dic = {'username':None,'login_statu':False}
def auth(func):
def wrapper(*args,**kwargs):
if user_dic['username'] and user_dic['login_statu']:
res = func(*args,**kwargs)
return res
for i in range(3):
name = input('请输入用户名:')
password = input('请输入密码:')
for item in user_list:
if item['name'] == name and item['passwd'] == password:
print('登录成功!')
user_dic['username'] = name
user_dic['login_statu'] = True
res = func(*args,**kwargs)
return res
if i < 2:
print('登录失败,请重试')
else:
print('3次登录机会已使用完!')
return wrapper
@auth
def order_l():
print('成功查看订单')
return 'dingdan'
@auth
def index():
print('进入京东')
@auth
def produ(name,*args):
print('%s 准备买%s' %(name,args))
index()
order_l()
produ('alex','wazi','衣服')
#给装饰器加参数
user_list =[
{'name':'alex','passwd':'1234'},
{'name':'keith','passwd':'12345'},
{'name':'mick','passwd':'1222'},
{'name':'june','passwd':'11111'},
{'name':'haha','passwd':'2345'}
]
user_dic = {'username':None,'login_statu':False}
def auth(authtype='mysql'):
def auth_func(func):
print('认证类型是:%s' %authtype)
def wrapper(*args,**kwargs):
if authtype == 'mysql':
if user_dic['username'] and user_dic['login_statu']:
res = func(*args,**kwargs)
return res
for i in range(3):
name = input('请输入用户名:')
password = input('请输入密码:')
for item in user_list:
if item['name'] == name and item['passwd'] == password:
print('登录成功!')
user_dic['username'] = name
user_dic['login_statu'] = True
res = func(*args,**kwargs)
return res
if i < 2:
print('登录失败,请重试')
else:
print('3次登录机会已使用完!')
elif authtype == 'ldap':
print('不支持的数据库格式')
return wrapper
return auth_func
@auth('ldap')
def order_l():
print('成功查看订单')
return 'dingdan'
order_l()
#文件的增删改查
import os
def file_handler(backward_data,record=None,type='fetch'):
if type == 'fetch':
with open('http.conf','r',encoding='utf-8') as read_f:
ret = []
tag = False
for read_line in read_f:
if read_line == backward_data:
tag = True
continue
elif tag and read_line.startswith('backward'):
tag = False
elif tag:
ret.append(read_line)
return ret
if type == 'change':
with open('http.conf','r') as read_f, open('http_new.conf','w') as write_f:
tag = False
has_write = False
for read_line in read_f:
if read_line == backward_data:
tag = True
write_f.write(read_line)
continue
elif not tag:
write_f.write(read_line)
elif tag and read_line.startswith('backward'):
tag = False
write_f.write(read_line)
else:
if not has_write:
for i in record:
write_f.write(i)
has_write = True
os.rename('http.conf','http.conf.bak')
os.rename('http_new.conf','http.conf')
os.remove('http.conf.bak')
return
def fetch(data):
backward_data = 'backward '+ data + '\n'
res = file_handler(backward_data)
return res
def add(data):
new_data = eval(data)
title = new_data[0]['backward']
backward_data = 'backward ' + title + '\n'
new_record = '%sserver %s %s weight %s max_connections %s\n' %('\t'*2,new_data[0]['record']['server'],
new_data[0]['record']['server'],
new_data[0]['record']['weight'],
new_data[0]['record']['max_connections'])
ret = fetch(title)
if new_record in ret:
return '您要增加的条目已存在'
else:
ret.insert(0,new_record)
res = file_handler(backward_data,record=ret,type='change')
return
def change(data):
new_data = eval(data)
title = new_data[0]['backward']
backward_data = 'backward ' + title + '\n'
old_record = '%sserver %s %s weight %s max_connections %s\n' %('\t'*2,new_data[0]['record']['server'],
new_data[0]['record']['server'],
new_data[0]['record']['weight'],
new_data[0]['record']['max_connections'])
new_record = '%sserver %s %s weight %s max_connections %s\n' %('\t'*2,new_data[1]['record']['server'],
new_data[1]['record']['server'],
new_data[1]['record']['weight'],
new_data[1]['record']['max_connections'])
ret = fetch(title)
if not ret or old_record not in ret:
return '你需要替换的内容不存在'
else:
for item in ret:
if item == old_record:
id = ret.index(item)
ret[id] = new_record
break
print('需要修改为:%s' %ret)
res = file_handler(backward_data,record=ret,type='change')
return
def delete(data):
new_data = eval(data)
title = new_data[0]['backward']
backward_data = 'backward ' + title + '\n'
old_record = '%sserver %s %s weight %s max_connections %s\n' %('\t'*2,new_data[0]['record']['server'],
new_data[0]['record']['server'],
new_data[0]['record']['weight'],
new_data[0]['record']['max_connections'])
ret = fetch(title)
if not ret or old_record not in ret:
print('你需要删除的内容不存在')
return
else:
for item in ret:
if item == old_record:
ret.remove(item)
res = file_handler(backward_data,record=ret,type='change')
return
if __name__ == '__main__':
msg = '''
1:增加
2:删除
3:修改
4:查询
5:退出
'''
dic = {
'1':add,
'2':delete,
'3':change,
'4':fetch,
'5':exit
}
while True:
print(msg)
act = input('请输入你的操作:').strip()
if not act: continue
elif act == '5':break
elif act not in str(range(1,6)):print('请输入目录中的数字:')
else:
data = input('请输入需要内容:').strip()
res = dic[act](data)
print(res)
文件样例
backward www.oldboy3.org
server 22.22.22.22 22.22.22.22 weight 100 max_connections 30600
server 11.5.5.9 11.5.5.9 weight 100 max_connections 6000
server 5.4.1.9 5.4.1.9 weight 100 max_connections 36000
server 1.1.1.1 1.1.1.1 weight 888 max_connections 600
server 89.5.5.9 89.5.5.9 weight 100 max_connections 30006
backward www.oldboy3.org1
server 11.5.5.59 11.5.5.59 weight 250 max_connections 8000
server 5.4.1.16 5.4.1.16 weight 250 max_connections 800
server 88.5.5.56 88.5.5.56 weight 250 max_connections 80
server 89.5.5.56 89.5.5.56 weight 250 max_connections 3008
[{'backward':'www.oldboy3.org','record':{'server':'88.5.5.9','weight':'100','max_connections':30600}},{'backward':'www.oldboy3.org','record':{'server':'1.1.1.1','weight':'888','max_connections':600}}]
[{'backward':'www.oldboy3.org','record':{'server':'22.22.22.22','weight':'100','max_connections':30600}}]