python3--裝飾器進階學習版

來源:互聯網
上載者:User

標籤:python 裝飾器


__author__ = "Aaron Fan"
import time #匯入time模組
user,passwd = ‘alex‘,‘abc123‘   #使用者名稱密碼
def auth(auth_type):    #建立auth函數,建立auth_type形參
   #print("auth func:",auth_type)   #列印形參auth_type的值
   def outer_wrapper(func):    #建立outer_wrapper函數,建立func形參
       def wrapper(*args, **kwargs):   #建立wrapper函數,建立非固定參數*args,**kwargs
           #print("wrapper func args:", *args, **kwargs)   #列印傳進來的這些非固定參數的值
           if auth_type == "local":    #如果auth函數中的形參auth_type的值等於local
               username = input("Username:").strip()   #輸入使用者名稱
               password = input("Password:").strip()   #輸入密碼
               if user == username and passwd == password: #如果使用者名稱和密碼全部正確
                   print("\033[32;1mUser has passed authentication\033[0m")    #以綠色的顏色列印一句登陸成功的提示



                   res = func(*args, **kwargs)  # from home    #這裡主要是為了顯示home()函數中的return值:from home
                   print("---after authenticaion ")    #列印一句話
                   return res  #返回定義的res變數的值


               else:   #否則帳號或者密碼錯誤
                   exit("\033[31;1mInvalid username or password\033[0m")
           elif auth_type == "ldap":   #如果auth函數中的形參auth_type的值等於ldap
               print("搞毛線ldap,不會。。。。") #ldap的處理語句,這裡暫時先用一句print代替了,記得後面練習是需要去細化一下

       return wrapper  #return wrapper
   return outer_wrapper    #return outer_wrapper

# index首頁,不需要使用者名稱密碼,可以直接登入,所以這裡也無需裝飾器
def index():
   print("welcome to index page")

#home頁面,需要通過local方式來匹配使用者登陸
@auth(auth_type="local") # home = wrapper()
                       #注意@auth代表auth(),而@auth(auth_type="local")代表outer_wrapper()
                       #所以這裡其實是指 home = outer_wrapper(home) = wrapper
def home():
   print("welcome to home  page")
   return "from home"

#bbs頁面,需要通過ldap方式來匹配使用者登陸
@auth(auth_type="ldap")
def bbs():
   print("welcome to bbs  page")

index()
print(home()) #其實執行的是wrapper()  這個方式會顯示home的return值
#home()  #其實執行的是wrapper()   這個不會顯示return值
bbs()   #其實執行的是wrapper()


本文出自 “近朱者赤” 部落格,請務必保留此出處http://fanheng.blog.51cto.com/974941/1881592

python3--裝飾器進階學習版

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.