Python裝飾器(4)

來源:互聯網
上載者:User

標籤:page   invalid   out   ldap   war   oca   功能   pre   home   

用裝飾器完成:(1)index登入不需認證、home和bbs 登入需要認證功能;(2)home登入用本地認證,bbs登入用ldap認證

 1 __author__ = "csy" 2 import time 3  4 user,passwd = ‘csy‘,‘123456‘ 5  6 def auth(auth_type):            #最外層auth用於傳遞auth_type認證類型 7     print("auth func",auth_type) 8     def outer_wrapper(func): 9         def wrapper(*args, **kwargs):10             print("wrapper func args", *args,**kwargs)11             if auth_type == ‘local‘:12                 username = input("Username:").strip()13                 password = input("Password:").strip()14 15                 if user == username and passwd == password:16                     print("\033[32;1mUser has passed authentication")17                     res = func(*args, **kwargs)18                     return res19                 else:20                     exit("\033[31;1mInvalid username or password\033[0m")21             elif auth_type == ‘ldap‘:22                 print("hehe")23         return wrapper24     return outer_wrapper25 26 def index():27     print("welcome to index page!")28 @auth(auth_type=‘local‘)29 def home():30     print("welcome to home page!")31 @auth(auth_type=‘ldap‘)32 def bbs():33     print("welcome to bbs page!")34 35 36 home()37 bbs()38 index()

輸出結果:

auth func local
auth func ldap
wrapper func args
Username:csy      #輸入
Password:123456      #輸入
User has passed authentication
welcome to home page!
wrapper func args
hehe
welcome to index page!

Python裝飾器(4)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.