python之裝飾器應用

# -*- coding:utf-8 -*-nhj
#  Author:Lin
import time
userna,passwd = 'lin','abc123'
def authentication_method(auth_val):
    print('this is authentication method')
    def out_wrapper(func):
        def wrapper(*args,**kwargs):
            username = input('Username:').strip()
            password = input('Password:').strip()
            if auth_val == 'local':
                if username == userna and password == passwd:
                    print('\033[32;1m User has passed authentication \033[0m')
                    print('\033[31;1m Welcome %s go back \033[0m' % username)
                    start_time = time.time()
                    func(*args,**kwargs)
                    stop_timee = time.time()
                    print('func run time is %s'%(stop_timee-start_time))
                else:
                    exit('')
            elif auth_val == 'ldap':
                if username == userna and password == passwd:
                    print('\033[32;1m User has passed authentication \033[0m')
                    print('\033[31;1m Welcome %s go back \033[0m' % username)
                    start_time = time.time()
                    func(*args, **kwargs)
                    stop_timee = time.time()
                    print('func run time is %s' % (stop_timee - start_time))
                else:
                    exit('')
        return wrapper
    return out_wrapper

def index():
    print('this is index page')

@authentication_method(auth_val = 'local')
def home():
    time.sleep(1)
    print('this is home page')

@authentication_method(auth_val = 'ldap')
def bbs(username,author_timer):
    time.sleep(1)
    print('this is bbs page')
    print('bbs author:%s,author_timer:%s' %(username,author_timer))

index()
home()
bbs('lins','2016-11-28')


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章