python 限制函数调用次数的实例讲解
如下代码,限制某个函数在某个时间段的调用次数,
灵感来源:python装饰器-限制函数调用次数的方法(10s调用一次)欢迎访问
原博客中指定的是缓存,我这里换成限制访问次数,异曲同工
#newtest.py #!/usr/bin/env python #-*- coding:utf-8 -*- import time def 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_time def foo(): print("I'm foo") if __name__=='__main__': for i in range(10): foo()
#test.py from newtest import foo import time for 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()
相关推荐
夜斗不是神 2020-11-17
huavhuahua 2020-11-20
Yasin 2020-11-16
xiaoseyihe 2020-11-16
千锋 2020-11-15
diyanpython 2020-11-12
chunjiekid 2020-11-10
wordmhg 2020-11-06
YENCSDN 2020-11-17
lsjweiyi 2020-11-17
houmenghu 2020-11-17
Erick 2020-11-17
HeyShHeyou 2020-11-17
以梦为马不负韶华 2020-10-20
lhtzbj 2020-11-17
pythonjw 2020-11-17
dingwun 2020-11-16
lhxxhl 2020-11-16