python-code-12

來源:互聯網
上載者:User

標籤:失敗   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

相關文章

聯繫我們

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