我一直在阅读以下回复:What's a good rate limiting algorithm?
如果没有异步功能,Carlos A. Ibarra的回复效果很好,但是有什么方法可以修改它以使其异步工作?
import time
def RateLimited(maxPerSecond):
minInterval = 1.0 / float(maxPerSecond)
def decorate(func):
lastTimeCalled = [0.0]
def rateLimitedFunction(*args,**kargs):
elapsed = time.clock() - lastTimeCalled[0]
leftToWait = minInterval - elapsed
if leftToWait>0:
time.sleep(leftToWait)
ret = func(*args,**kargs)
lastTimeCalled[0] = time.clock()
return ret
return rateLimitedFunction
return decorate
@RateLimited(2) # 2 per second at most
def PrintNumber(num):
print num
if __name__ == "__main__":
print "This should print 1,2,3... at about 2 per second."
for i in range(1,100):
PrintNumber(i)
将time.sleep(leftToWait)
更改为await asyncio.sleep(leftToWait)
并等待PrintNumber(i)
的情况在第一个实例中有效,但此后没有效果。我真的是Python的新手,我会尽力遵守API的速率限制。
我的实现:
def rate_limited(max_per_second):
min_interval = 1.0 / float(max_per_second)
def decorate(func):
last_time_called = [0.0]
async def rate_limited_function(*args, **kargs):
elapsed = time.clock() - last_time_called[0]
left_to_wait = min_interval - elapsed
if left_to_wait > 0:
await asyncio.sleep(left_to_wait)
ret = func(*args, **kargs)
last_time_called[0] = time.clock()
return ret
return rate_limited_function
return decorate
class Test:
def __init__(self, bot):
self.bot = bot
@commands.command(hidden=True, pass_context=True)
@checks.serverowner()
async def test1(self, ctx):
await self.print_number()
@rate_limited(0.1)
def print_number(self):
print("TEST")
答案 0 :(得分:3)
这是一个简单的discord.py解决方案。这使用on_command_error
事件保留命令并永久运行它,直到冷却时间解决为止,基本上是通过使用asyncio.sleep
等待冷却时间:
bot = commands.Bot('?')
@bot.command(hidden=True, pass_context=True)
@commands.cooldown(1, 5, commands.BucketType.user) # means "allow to be called 1 time every 5 seconds for this user, anywhere"
async def test(ctx):
print("TEST")
@bot.event
async def on_command_error(exc, context: commands.Context):
if isinstance(exc, commands.errors.CommandOnCooldown):
while True:
await asyncio.sleep(exc.retry_after)
try:
return await context.command.invoke(context)
except commands.errors.CommandOnCooldown as e:
exc = e
不一致时(假设前缀为?
)
0s> ?test
1s> ?test
2s> ?test
在控制台中:
0s> TEST
5s> TEST
10s> TEST
答案 1 :(得分:1)
您可以在此处执行的最简单的操作之一是使代码重新轮询共享变量,从而循环执行,而不是假设,该当前实例将是单个实例之后的下一个实例。睡觉:
import time, asyncio
def rate_limited(max_per_second):
min_interval = 1.0 / float(max_per_second)
def decorate(func):
last_time_called = [0.0]
async def rate_limited_function(*args, **kargs):
elapsed = time.time() - last_time_called[0]
left_to_wait = min_interval - elapsed
while left_to_wait > 0:
await asyncio.sleep(left_to_wait)
elapsed = time.time() - last_time_called[0]
left_to_wait = min_interval - elapsed
ret = func(*args, **kargs)
last_time_called[0] = time.time()
return ret
return rate_limited_function
return decorate
@rate_limited(0.2)
def print_number():
print("Actually called at time: %r" % (time.time(),))
loop = asyncio.get_event_loop()
asyncio.ensure_future(print_number())
asyncio.ensure_future(print_number())
asyncio.ensure_future(print_number())
asyncio.ensure_future(print_number())
loop.run_forever()
...正确发射:
Actually called at time: 1530570623.868958
Actually called at time: 1530570628.873996
Actually called at time: 1530570633.876241
Actually called at time: 1530570638.879455
...显示两次通话之间的间隔为5秒(每秒0.2秒)。