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设计】。

相关文章

pytest中文文档之编写断言

编写断言 使用assert编写断言 pytest允许你使用python标准的assert表达式写断言; 例如,你可以这样做: # test_sample.py def func...

解决Python出现_warn_unsafe_extraction问题的方法

解决Python出现_warn_unsafe_extraction问题的方法

在Python项目中运行出现了“AttributeError: ResourceManager instance has no attribute ‘_warn_unsafe_extra...

python打开网页和暂停实例

本文实例讲述了python打开网页和暂停的方法。分享给大家供大家参考。 具体实现代码如下: import webbrowser import os webbrowser.open_...

python完成FizzBuzzWhizz问题(拉勾网面试题)示例

拉勾网面试题1. 你首先说出三个不同的特殊数,要求必须是个位数,比如3、5、7。2. 让所有学生拍成一队,然后按顺序报数。3. 学生报数时,如果所报数字是第一个特殊数(3)的倍数,那么不...

python requests模拟登陆github的实现方法

python requests模拟登陆github的实现方法

1. Cookie 介绍 HTTP 协议是无状态的。因此,若不借助其他手段,远程的服务器就无法知道以前和客户端做了哪些通信。Cookie 就是「其他手段」之一。 Cookie 一个典型的...