1. 程式人生 > >Python3.5——裝飾器及應用詳解(下)

Python3.5——裝飾器及應用詳解(下)

1、裝飾器應用——模擬網站登入頁面,訪問需要認證登入頁面

#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:ZhengzhengLiu
#模擬網站,訪問頁面和部分需要登入的頁面

import timer
user,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 wrapper

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

@auth
def home():
    print("welcome to index home!")
    return "from home"

@auth
def 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 timer
user,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_wrapper

def 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()
執行結果: