Python limits the number of function calls

Source: Internet
Author: User
Below for you to share a Python limit function calls the number of examples, with a good reference value, I hope to be helpful to everyone. Come and see it together.

The following code, which limits the number of times a function is called in a certain time period,

Inspiration: Python adorner-method to limit the number of function calls (10s calls once) Welcome access

The original blog is specified in the cache, I change here to limit the number of visits, the same

#newtest. py#!/usr/bin/env python#-*-coding:utf-8-*-import timedef 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 (' Number of calls:%s '% cache[key][0])  Print (' Limit:%s '% limit_times[0])  if cache[key][0] <= limit_times[0]:   res=func (*args,**kwargs)   CACHE[KEY][1] = Time.time ()   return res  else:   print ("exceeds number of calls")   return None return _called_ Time@stat_called_timedef foo (): Print ("I ' m foo") if __name__== ' __main__ ': for I in range:  foo ()

#test. Pyfrom newtest Import Fooimport timefor i in range (+): foo () print (' * ' *20) foo () foo () print (' * ' *20) for I in range (60) : Print (i) time.sleep (1) for I in Range (one): foo ()

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.