python学习,day4:装饰器的使用示例2

这个例子比较复杂

# coding=utf-8
# Author: RyAn Bi
user,passwd = 'bb','123'   #输入用户名密码
def auth(auth_type):        #装饰器第一层,确定鉴权类型
    print('auth func:', auth_type )    #打印鉴权类型
    def out_wrapper(func):       #装饰器第二层,调用函数
        def warrper(*args,**kwargs):    #装饰器第三层,增加功能,具体实施
            if auth_type == 'local':        #判断鉴权类型
                username = input('username:').strip()   #输入用户名
                password = input('password:').strip()   #输入密码
                if user==username and passwd ==password:   #判断用户密码
                    print('\033[32;1mthe user is correct\033[0m')
                    res =func(*args,**kwargs)  #from home    #运行程序,并将程序运行结果导入res
                    print('=======>after authentication')
                    return res     #返回func       #将res结果返回给func,home程序输出‘from home
                else:
                   exit('\033[31;1mthe user is invalid\033[0m')
            elif auth_type =='ldap':
                print('搞毛线啊,不会')
        return warrper
    return out_wrapper

def index():
    print('welcom to index page')
@auth(auth_type = 'local')   #home =auth()
def home():
    print('welcom to home page')
    return 'from home'
@auth(auth_type = 'ldap')
def bbs():
    print('welcom to bbs page')

index()
print(home())  #调用home相当于调用warrper

bbs()

猜你喜欢

转载自www.cnblogs.com/bbgoal/p/10438142.html