Python3.5——装饰器及应用详解(下)

来源:互联网 发布:gitlab 使用 windows 编辑:程序博客网 时间:2024/06/05 15:15

1、装饰器应用——模拟网站登录页面,访问需要认证登录页面

#!/usr/bin/env python# -*- coding:utf-8 -*-# Author:ZhengzhengLiu#模拟网站,访问页面和部分需要登录的页面import timeruser,passwd = "liu","liu123"def auth(func):    def wrapper(*args,**kwargs):        username = input("Username:").strip()        password = input("Password:").strip()        if username == user and password == passwd:            print("\033[32;1mUser has passed authentication!\033[0m")            res = func(*args,**kwargs)            print("-----after authentication---")            return res        else:            exit("\033[31;1mInvalid username or password!\033[0m")    return wrapperdef index():    print("welcome to index page!")@authdef home():    print("welcome to index home!")    return "from home"@authdef bbs():    print("welcome to index bbs!")#函数调用index()print(home())bbs()#运行结果:#welcome to index page!#Username:liu#Password:liu123#User has passed authentication!#welcome to home page!#-----after authentication---#from home#Username:liu#Password:liu123#User has passed authentication!#welcome to bbs page!#-----after authentication---

2、装饰器带参数

#!/usr/bin/env python# -*- coding:utf-8 -*-# Author:ZhengzhengLiu#模拟网站,访问页面和部分需要登录的页面,多种认证方式import timeruser,passwd = "liu","liu123"def auth(auth_type):    print("auth func:",auth_type)    def outer_wrapper(func):        def wrapper(*args, **kwargs):            print("wrapper func args:",*args, **kwargs)            if auth_type == "local":                username = input("Username:").strip()                password = input("Password:").strip()                if username == user and password == passwd:                    print("\033[32;1mUser has passed authentication!\033[0m")                    #被装饰的函数中有返回值,装饰器中传入的参数函数要有返回值                    res = func(*args, **kwargs)    #from home                    print("-----after authentication---")                    return res                else:                    exit("\033[31;1mInvalid username or password!\033[0m")            elif auth_type == "ldap":                print("ldap....")        return wrapper    return outer_wrapperdef index():    print("welcome to index page!")@auth(auth_type="local")       #利用本地登录  home =  wrapper()def home():    print("welcome to home page!")    return "from home"@auth(auth_type="ldap")       #利用远程的ldap登录def bbs():    print("welcome to bbs page!")#函数调用index()print(home())      #wrapper()bbs()
运行结果:



原创粉丝点击