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

yipeiwu_com5年前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()

以上这篇python 限制函数调用次数的实例讲解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python subprocess模块常见用法分析

本文实例讲述了Python subprocess模块常见用法。分享给大家供大家参考,具体如下: subprocess模块是python从2.4版本开始引入的模块。主要用来取代 一些旧的模...

pyqt5 从本地选择图片 并显示在label上的实例

pyqt5 从本地选择图片 并显示在label上的实例

1.主要用到 QFileDialog 方法打开本地文件 2.界面 打开前: 打开后: 3. 代码 import sys from PyQt5 import QtWidgets,...

Python 网络编程之TCP客户端/服务端功能示例【基于socket套接字】

本文实例讲述了Python 网络编程之TCP客户端/服务端功能。分享给大家供大家参考,具体如下: demo.py(TCP客户端): import socket def main():...

python多任务之协程的使用详解

1|0使用yield完成多任务 import time def test1(): while True: print("--1--") time.sleep(0.5)...

python语言线程标准库threading.local解读总结

本段源码可以学习的地方: 1. 考虑到效率问题,可以通过上下文的机制,在属性被访问的时候临时构建; 2. 可以重写一些魔术方法,比如 __new__ 方法,在调用 object.__ne...