標籤:失敗 stat type 數加 stop open 超過 dex top
一:編寫函數,(函數執行的時間是隨機的)
二:編寫裝飾器,為函數加上統計時間的功能
import timedef timmer(func): def wrapper(*args,**kwargs): start = time.time() res = func(*args,**kwargs) stop = time.time() print(‘run time is %s‘ %(stop - start)) return res return wrapper@timmerdef index(): print(‘welcome to index‘) time.sleep(3) return 123@timmerdef home(name): print(‘welcome %s to home page‘ %name) time.sleep(2)res = index()home(‘egon‘)
View Code
三:編寫裝飾器,為函數加上認證的功能
import timedef auth(func): def wrapper(*args,**kwargs): tag = True while tag: name_inp = input(‘username>>: ‘).strip() pwd_inp = input(‘password>>: ‘) with open(‘db‘,‘rt‘,encoding=‘utf-8‘) as f: for line in f: line = line.strip(‘\n‘).split(‘:‘) if name_inp == line[0] and pwd_inp == line[1]: print(‘認證成功‘) tag = False break else: print(‘認證失敗‘) res=func(*args,**kwargs) return res return wrapper@auth # index=auth(index)def index(): print(‘welcome to index‘) time.sleep(3) return 123@auth # home=auth(home)def home(name): print(‘welcome %s to home page‘ %name) time.sleep(2)res=index()home(‘egon‘)
View Code
四:編寫裝飾器,為多個函數加上認證的功能(使用者的帳號密碼來源於檔案),要求登入成功一次,後續的函數都無需再輸入使用者名稱和密碼
注意:從檔案中讀出字串形式的字典,可以用eval(‘{"name":"egon","password":"123"}‘)轉成字典格式
db=‘db‘login_status={‘user‘:None,‘status‘:False}def auth(auth_type=‘file‘): def auth2(func): def wrapper(*args,**kwargs): if login_status[‘user‘] and login_status[‘status‘]: return func(*args,**kwargs) if auth_type == ‘file‘: with open(db,encoding=‘utf-8‘) as f: dic=eval(f.read()) name=input(‘username: ‘).strip() password=input(‘password: ‘).strip() if name in dic and password == dic[name]: login_status[‘user‘]=name login_status[‘status‘]=True res=func(*args,**kwargs) return res else: print(‘username or password error‘) elif auth_type == ‘sql‘: pass else: pass return wrapper return auth2@auth()def index(): print(‘index‘)@auth(auth_type=‘file‘)def home(name): print(‘welcome %s to home‘ %name)index()home(‘egon‘)
View Code
五:編寫裝飾器,為多個函數加上認證功能,要求登入成功一次,在逾時時間內無需重複登入,超過了逾時時間,則必須重新登入
import time,randomuser={‘user‘:None,‘login_time‘:None,‘timeout‘:0.000003,}def timmer(func): def wrapper(*args,**kwargs): s1=time.time() res=func(*args,**kwargs) s2=time.time() print(‘%s‘ %(s2-s1)) return res return wrapperdef auth(func): def wrapper(*args,**kwargs): if user[‘user‘]: timeout=time.time()-user[‘login_time‘] if timeout < user[‘timeout‘]: return func(*args,**kwargs) name=input(‘name>>: ‘).strip() password=input(‘password>>: ‘).strip() if name == ‘egon‘ and password == ‘123‘: user[‘user‘]=name user[‘login_time‘]=time.time() res=func(*args,**kwargs) return res return wrapper@authdef index(): time.sleep(random.randrange(3)) print(‘welcome to index‘)@authdef home(name): time.sleep(random.randrange(3)) print(‘welcome %s to home ‘ %name)index()home(‘egon‘)
View Code
python-code-12