装饰器5--被装饰函数带有返回值,且装饰器本身带参数的情况

 

代码:

 

#home用本地认证方式;BBS用远程ldap认证。
#被装饰函数带返回值的,记得要return一下return func(*args, **kwargs)
#装饰器本身带参数的情况:
import time
user,passwd="alex","abc123"
def auth(auth_type):
    #print("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 username == user and password == passwd:
                    print("passed")
                    return func(*args, **kwargs)  # from home,把func()运行后的结果返回。
                else:
                    exit("invalid")
            elif auth_type=="ldap":
                print("搞毛线ldap,不会---------")
        return wrapper
    return outer_wrapper

def index():
    print("welcome to index page")

@auth(auth_type="local")  #home=auth(home)
def home():  #执行home相当于执行wrapper
    print("welcome to home page")
    return "from home"

@auth(auth_type="ldap")
def bbs():
    print("welcome to bbs page")

index()
home()
bbs()

 

 

 

运行结果:

 

welcome to index page
username:alex
password:abc123
passed
welcome to home page
搞毛线ldap,不会---------

Process finished with exit code 0

 

posted on 2017-07-21 15:29  momo8238  阅读(601)  评论(0编辑  收藏  举报