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

作者:随便起个名字啊 时间:2023-11-11 00:34:23 

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

灵感来源: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()

来源:https://blog.csdn.net/qq_28035571/article/details/79483944

标签:python,函数,调用,次数
0
投稿

猜你喜欢

  • JavaScript数组合并的8种常见方法小结

    2024-04-16 09:32:55
  • 基于jQuery的自动完成插件

    2011-02-05 10:55:00
  • Django values()和value_list()的使用

    2021-08-21 23:03:12
  • 在Python的Flask框架中构建Web表单的教程

    2023-10-04 06:03:12
  • Python的控制结构之For、While、If循环问题

    2023-09-16 21:42:45
  • Python 连接字符串(join %)

    2021-01-13 23:30:46
  • MySQL授权命令grant的使用方法小结

    2024-01-22 14:09:22
  • 用Python代码自动生成文献的IEEE引用格式的实现

    2021-05-26 15:24:49
  • pandas 取出表中一列数据所有的值并转换为array类型的方法

    2023-10-04 15:12:52
  • python logging模块书写日志以及日志分割详解

    2023-02-23 12:52:16
  • JavaScript控制输入框中只能输入中文、数字和英文的方法【基于正则实现】

    2024-04-16 08:50:16
  • jsp自定义标签之ifelse与遍历自定义标签示例

    2023-06-25 21:09:34
  • Django REST Swagger实现指定api参数

    2023-03-10 05:48:58
  • BatchNorm2d原理、作用及pytorch中BatchNorm2d函数的参数使用

    2021-05-28 10:07:19
  • Python3.6基于正则实现的计算器示例【无优化简单注释版】

    2023-07-19 05:29:25
  • MSSQL经典语句

    2024-01-22 02:59:12
  • Python使用剪切板的方法

    2022-01-25 02:17:39
  • oracle锁表该如何解决

    2024-01-23 20:28:38
  • Python中jieba库的使用方法

    2021-06-23 13:47:24
  • 升级和卸载Oracle数据库软件的命令整理

    2024-01-16 18:15:37
  • asp之家 网络编程 m.aspxhome.com