脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python 限制函数调用次数的实例讲解

python 限制函数调用次数的实例讲解

2021-02-03 00:38随便起个名字啊 Python

下面小编就为大家分享一篇python 限制函数调用次数的实例讲解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

如下代码,限制某个函数在某个时间段的调用次数,

灵感来源:python装饰器-限制函数调用次数的方法(10s调用一次) 欢迎访问

原博客中指定的是缓存,我这里换成限制访问次数,异曲同工

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#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()
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#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()

以上这篇python 限制函数调用次数的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。

原文链接:https://blog.csdn.net/qq_28035571/article/details/79483944

延伸 · 阅读

精彩推荐