装饰器,文件处理(增,删,改,查)

1.装饰器基本定义

装饰器的组成:高阶函数,函数嵌套,闭包

高阶函数有两种类型:1函数的参数是函数名 2函数返回值是函数名

装饰器不能违反的原则:1不修改被修饰函数的源代码 2不修改被修饰函数的调用方式

装饰器作用:为已经存在的对象加上额外的功能

#高阶函数类型1 函数接受参数是函数名
def foo():
    print('你好啊,凌师傅')
def test(func):
    print(func)
    func()
test(foo)

#有一个函数,实际执行代码是首次调用函数中参数为函数名的函数代码,即foo
import time
def foo():
    time.sleep(3)
    print(list(i for i in range(10))) #(i for i in range(10))生成器,列表可以产生迭代器,取出生成器中的值
def test(func):
    print(foo)
    start_time = time.time()
    func()
    stop_time start_time = time.time()
    func()
    stop_time = time.time()
    time_diff = stop_time - start_time
    time_diff = stop_time - start_time
    print(time_diff)
test(foo)

#高阶函数类型2,函数返回值是函数名
def foo():
    print('abc')
def test(func):
    return func
res = test(foo)
print(res)
res()

#装饰器必要条件1高阶函数   1不修改foo()源代码;2不改变foo调用方式(函数的参数是函数名的调用方式)
import time
def foo():
    time.sleep(3)
    print('from foo')
def test(func):
    start_time = time.time()
    func()
    stop_time = time.time()
    print('函数的运行时间是%s'% (stop_time - start_time))
    return func
test(foo)

#装饰器必要条件2函数嵌套函数
def father(name):
    print('from father %s'%name)
    def son():  #函数即变量
        print('from the son')
    print(locals())
    son()
father('alex')

# #装饰器必要条件3闭包
def father(auth_type):
    def son():
        def grandson():
            print('my grandfather is %s' % auth_type)
        grandson()
    son()
father('yuyukun')

 2.装饰器基本框架

#装饰器
import time
#装饰器框架
def timer(func): #func = test
def wrapper():
print('函数过转到test()运行3s')
start_time = time.time()
func() #运行test()
stop_time = time.time()
print('运行时间%s' %(stop_time-start_time))
return wrapper
@timer #@装饰器名 @timer等同于tet = timer(test)
def test():
time.sleep(3)
print('test function finished')
# test = timer(test) #功能函数(辅助函数名) 返回的是wrapper()
test()
@timer 等同于test=timer(test)
 #函数闭包加上返回值 import time #装饰器框架 def timer(func): #func = test def wrapper(): print('函数过转到test()运行3s') start_time = time.time() res = func() #运行test() stop_time = time.time() print('test()运行时间%s' %(stop_time-start_time)) return res return wrapper @timer #@装饰器名 @timer等同于test = timer(test) def test(): time.sleep(3) return 'this is the value of return' # res = test #返回局部变量wrapper()地址 res1 = test()#运行wrapper()函数 print(res1)

 3.装饰器综合实例:判断参数+文件操作+全局变量

def global_name():
    user_list = []
    # global name
    with open('database of username and password','r',encoding='utf-8') as f:
        for user_dic in f:
            user_dic = eval(user_dic)
            user_list.append(user_dic)
        # print(user_list)
    current_dic = {'username':None,'login':False}
    def auth(auth_type='filedb'):
        def auth_func(func): #装饰器类型是函数  #step1  #有用户登录成功,保持状态
            def wrapper(*args,**kwargs):    #step2
                # print(auth_type) #auth_type = *args = func = filedb
                if auth_type == 'filedb':
                    print('认证类型是', auth_type)
                    if current_dic['username'] and current_dic['login']: #情况1,判断当前是否有用户或者有用户登录
                        res = func(*args, **kwargs)  # step3 func对应auth_func(func)中的形参变量func
                        return res
                    username = input('username:>>>').strip() #.strip()去除首末空格,换行
                    passward = input('password:>>>').strip() #.strip()去除首末空格,换行
                    for user_dic in user_list:
                        global name
                        name = username
                        if username == user_dic['username'] and passward == user_dic['login']: #情况2,判断当前用户是否是列表中的用户
                            current_dic['username'] = username
                            current_dic['login'] = True
                            res = func(*args,**kwargs)  # step3 func对应auth_func(func)中的形参变量func
                            return res
                    else:
                        print('用户名或密码错误')
                elif auth_type == 'ldba':
                    print('认证类型是',auth_type)
                    res = func(*args, **kwargs)  # step3 func对应auth_func(func)中的形参变量func
                    return res
                else:
                    print('认证类型是', auth_type)
                    res = func(*args, **kwargs)  # step3 func对应auth_func(func)中的形参变量func
                    return res
            return wrapper
        return auth_func
    @auth(auth_type='filedb') #auth_func=auth(auth_type='filedb')--->@auth_func 附加了auth_type 形参--->index=auth_func(index)
    def index():
        print('welcome to jindong mall')
    @auth(auth_type='ldba')
    def home(name):
        print('this is [%s] website'% name)
    @auth(auth_type='ass')
    def shopping_car(name):
        print('there are [%s,%s,%s] in the [%s]_shopping car'% ('egg','milk','break',name))
    print('before--->',current_dic)
    index()
    print('after--->',current_dic)
    home('yyk')
    shopping_car('yyk')
global_name()

4.文件的增删改查

#!user/bin/env python
# -*- coding:utf-8 -*-
import os
def fetch(data):
    # print('\033[1;43m这是查询功能\033[0m')
    # print('\033[1;43m用户数据是\033[0m',data)
    backend_data = 'backend %s' %data
    # print(backend_data)
    li = []
    with open('haproxy.conf','r') as read_f:
        tag = False
        for read_line in read_f:
            # print(read_line)
            if read_line.strip() == backend_data:
                tag = True
                continue
            if tag and read_line.startswith('backend'): #找到backend 并且 下一行以backend开头(加上tag防止在目标行之前先找到backend)
                break
            if tag:
                print('\033[1;45m%s\033[0m' %read_line,end='')
                li.append(read_line)
    return li
def add():
    pass
def change(data):
    # print('这是修改功能')
    print('用户输入的数据是',data)
    backend = data[0]['backend'] #文件中的一条记录 查找1 www.oldboy1.org
    backend_data = 'backend %s'%backend #backend www.oldboy1.org
    #        server 2.2.2.4 2.2.2.4 weight 20 maxconn 3000
    #        server 2.2.2.5 2.2.2.5 weight 30 maxconn 4000
    # [{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}}]
    old_server_record = '%sserver %s %s weight %s maxconn %s\n'%(' '*8,data[0]['record']['server'],
                                                                data[0]['record']['server'],
                                                                data[0]['record']['weight'],
                                                                data[0]['record']['maxconn'])
    new_server_record = '%sserver %s %s weight %s maxconn %s\n'%(' '*8,data[1]['record']['server'],
                                                                data[1]['record']['server'],
                                                                data[1]['record']['weight'],
                                                                data[1]['record']['maxconn'])
    print('用户想要修改的记录是',old_server_record)   #查找2{'server':'2.2.2.4','weight':20,'maxconn':3000}
    res = fetch(backend) #fetch('www.oldboy1.org')
    # print('来自查找函数',res)
    print('来自修改函数--->',res)
    # print(old_server_record,end='')
    # print(new_server_record,end='')
    if not res or old_server_record not in res:
        print('修改记录不存在')
    else:
        index = res.index(old_server_record)
        res[index] = new_server_record
        # for i in res:
        #     print(i)
        # print(backend_data)
    res.insert(0,'%s\n' %backend_data)
    with open('haproxy.conf','r') as\
            read_f,open('haproxy_new.conf','w') as write_f:
        tag = False
        has_writen_tag = False
        for read_line in read_f:
            if read_line.strip() == backend_data:
                tag = True
                # write_f.write(read_line)
                continue
            if tag and read_line.startswith('backend'):
                tag = False
            if not tag:
                write_f.write(read_line)
            else:
                if not has_writen_tag:
                    for record in res:
                        write_f.write(record)
                    has_writen_tag = True
    os.rename('haproxy.conf','haproxy.conf.bak') #对haproxy.conf文件重新命名为haproxy.conf.bak
    os.rename('haproxy_new.conf','haproxy.conf') #对haproxy_new.conf重新命名为haproxy.conf
    os.remove('haproxy.conf.bak') #移除.bak文件
def delete():
    pass
if __name__ == '__main__':
    msg = '''
    1:查询
    2:添加
    3.修改
    4.删除
    5.退出
    '''
    # print(msg)
    msg_dic = {
        '1':fetch,
        '2':add,
        '3':change,
        '4':delete,
        '5':exit
    }
    bool = True
    while bool:
        print(msg)
        choice = input('please input your item:')
        if not choice:continue
        if choice == '5':break
        data = input('请输入你的数据:')
        if data == '':
            continue
        if choice != '1':
            data = eval(data)
        res = msg_dic[choice](data)
        print(res)

 

posted on 2019-03-08 16:49  yukun093  阅读(172)  评论(0编辑  收藏  举报

导航