Below for you to share a Python limit function calls the number of examples, with a good reference value, I hope to be helpful to everyone. Come and see it together.
The following code, which limits the number of times a function is called in a certain time period,
Inspiration: Python adorner-method to limit the number of function calls (10s calls once) Welcome access
The original blog is specified in the cache, I change here to limit the number of visits, the same
#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 (' Number of calls:%s '% cache[key][0]) Print (' Limit:%s '% limit_times[0]) if cache[key][0] <= limit_times[0]: res=func (*args,**kwargs) CACHE[KEY][1] = Time.time () return res else: print ("exceeds number of calls") return None return _called_ Time@stat_called_timedef foo (): Print ("I ' m foo") if __name__== ' __main__ ': for I in range: foo ()
#test. Pyfrom newtest Import Fooimport timefor i in range (+): foo () print (' * ' *20) foo () foo () print (' * ' *20) for I in range (60) : Print (i) time.sleep (1) for I in Range (one): foo ()