python 限制函數調用次數

來源:互聯網
上載者:User
下面為大家分享一篇python 限制函數調用次數的執行個體講解,具有很好的參考價值,希望對大家有所協助。一起過來看看吧

如下代碼,限制某個函數在某個時間段的調用次數,

靈感來源:python裝飾器-限制函數調用次數的方法(10s調用一次) 歡迎訪問

原部落格中指定的是緩衝,我這裡換成限制訪問次數,異曲同工

#newtest.py#!/usr/bin/env python#-*- coding:utf-8 -*-import timedef stat_called_time(func): cache={} limit_times=[10] def _called_time(*args,**kwargs):  key=func.__name__  if key in cache.keys():   [call_times,updatetime]=cache[key]   if time.time()-updatetime <60:    cache[key][0]+=1   else:    cache[key]=[1,time.time()]  else:   call_times=1   cache[key]=[call_times,time.time()]  print('調用次數: %s' % cache[key][0])  print('限制次數: %s' % limit_times[0])  if cache[key][0] <= limit_times[0]:   res=func(*args,**kwargs)   cache[key][1] = time.time()   return res  else:   print("超過調用次數了")   return None return _called_time@stat_called_timedef foo(): print("I'm foo")if __name__=='__main__': for i in range(10):  foo()

#test.pyfrom newtest import fooimport timefor i in range(30): foo()print('*'*20)foo()foo()print('*'*20)for i in range(60): print(i) time.sleep(1)for i in range(11): foo()

聯繫我們

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