进军装饰器3/3

装饰器实验需求:

某网站有20个页面,除index页面无需登录验证外,其它页面均需要进行登录验证,本实验通过装饰器进行模拟,以达到熟练使用装饰器的目的,而不是达到登录验证的目的:

初级版模拟:

# -*-coding:utf-8-*-
# _Author_:George
user = "George"
passwd = "123abc"
def auth(func):
    def wrapper(*args,**kwargs):
        username = input("username:").strip()
        password = input("password:").strip()
        if username == user and password == passwd:
            print("%s has passed authentication!"%user)
            return func(*args,**kwargs)
        else:
            print("Sorry! username or password inccorect!")
    return wrapper
def index():
    print("Welcome to index page.")
@auth
def home():
    print("Welcome to home page.")
    return "from home"
@auth
def bbs():
    print("Welcome to bbs page.")
index()
print(home())
bbs()

 

终级版模拟:

# -*-coding:utf-8-*-
# _Author_:George
user = "George"
passwd = "123abc"
def auth(auth_type):
    def outer_wrapper(func):
        def wrapper(*args,**kwargs):
            if auth_type == "LOCAL":
                username = input("username:").strip()
                password = input("password:").strip()
                if username == user and password == passwd:
                    print("%s has passed authentication!"%user)
                    return func(*args,**kwargs)
                else:
                    print("Sorry! username or password inccorect!")
            elif auth_type == "LDAP":
                print("-------LDAP Flow,此处省略-------")
        return wrapper
    return outer_wrapper
def index():
    print("Welcome to index page.")
@auth(auth_type="LOCAL")
def home():
    print("Welcome to home page.")
    return "\033[31;1mfrom home\033[0m"
@auth(auth_type="LDAP")
def bbs():
    print("Welcome to bbs page.")
index()
print(home())
bbs()

 

posted on 2018-01-07 12:15  承祥君  阅读(90)  评论(0编辑  收藏  举报

导航