Python limits the number of function calls

不言
Release: 2018-04-21 14:33:23
Original
3327 people have browsed it

The following is an example of how to limit the number of function calls in Python. It has a good reference value and I hope it will be helpful to everyone. Let’s take a look together

The following code limits the number of calls to a certain function in a certain period of time.

Source of inspiration: python decorator-method to limit the number of function calls (call once every 10 seconds ) Welcome to visit

The original blog specified caching. I changed it to limiting the number of visits here, which is the same but the same result

#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(&#39;调用次数: %s&#39; % cache[key][0])
  print(&#39;限制次数: %s&#39; % 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&#39;m foo")
if __name__==&#39;__main__&#39;:
 for i in range(10):
  foo()
Copy after login

#test.py
from newtest import foo
import time
for i in range(30):
 foo()
print(&#39;*&#39;*20)
foo()
foo()
print(&#39;*&#39;*20)
for i in range(60):
 print(i)
 time.sleep(1)
for i in range(11):
 foo()
Copy after login

Related recommendations:

Python’s method of using decorators and threads to limit function execution time


The above is the detailed content of Python limits the number of function calls. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!