Acfe 发表于 2018-8-16 06:00:05

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')
页: [1]
查看完整版本: python之装饰器应用