第四周练习 part2 --- 装饰器实例

装饰器实例:为网站的多个页面添加登陆认证

user, passwd = 'Lief', '123'


def auth(auth_type):
    def outer_wrapper(func):
        def wrapper(*args, **kwargs):
            print('wrapper', *args, **kwargs)
            if auth_type == 'Local':
                username = input('Username:').strip()
                password = input('Password:').strip()
                if user == username and passwd == password:
                    print('\033[31;1mUser has passed authentication\033[0m')
                    res = func(*args, **kwargs)
                    print('返回值去哪了')
                    return res
                else:
                    exit('\033[31;1mInvalid username or wrong password\033[0m')
            elif auth_type == 'ldap':
                print('LDAP')
        return wrapper
    return outer_wrapper


def index():
    print('-------Welcome to index page-------')


@auth(auth_type='Local')
def home():
    print('-------Welcome to home page-------')
    return 'return value'


@auth(auth_type='ldap')
def bbs():
    print('-------Welcome to bbs page-------')


home()
bbs()
index()

 

posted @ 2018-03-26 08:15  Lief_1997  阅读(111)  评论(0)    收藏  举报