扼流圈:节流机构的简单实现。
choke的Python项目详细描述
choke是一个实现普通用途节流机制的包。使用choke的基本工作流如下:
- create manager-一个对象,负责在发生某些事件(如:调用函数)时跟踪时间戳。
- 指示管理器“阻塞”一些可调用的对象,即定义每个给定时间窗口可能出现的最大调用次数。
- 像往常一样使用您的可调用函数,请记住,当超过上述定义的限制时,阻塞的可调用函数将引发CallLimitExcepederRor。
下面是一个示例,其中包含使用choke所需的所有内容:
fromtimeimportsleepfromredisimportStrictRedisfromchokeimportRedisChokeManager,CallLimitExceededErrorREDIS=StrictRedis()# Tweak this to reflect your setupCHOKE_MANAGER=RedisChokeManager(redis=REDIS)# Example configuration: enforce limit of no more than 10 calls in two seconds window@CHOKE_MANAGER.choke(limit=10,window_length=2)deffoo(x,y):"""Just print something to show that foo was called."""print(f'foo called with ({x}, {y})')if__name__=='__main__':# We expect pattern of 10 successes followed by 10 failures followed again by 10 successes# Some deviations from this pattern may obviously occur as calling foo takes nonzero timeforiinrange(30):try:foo(i,y=i**2)exceptCallLimitExceededError:print('Foo not called. Limit exceeded!')sleep(0.1)