简单易用的异步调节器
asyncio-throttle的Python项目详细描述
简单易用的异步节流器。
示例
importtimeimportrandomimportasynciofromasyncio_throttleimportThrottlerasyncdefworker(no,throttler,n):for_inrange(n):awaitasyncio.sleep(random.random()*2)asyncwiththrottler:print(time.time(),'Worker #%d: Bang!'%no)asyncdefmain():throttler=Throttler(rate_limit=5)tasks=[loop.create_task(worker(no,throttler,10))fornoinrange(5)]awaitasyncio.wait(tasks)loop=asyncio.get_event_loop()loop.run_until_complete(main())loop.close()
这里我把工作速度限制在5/秒,而有5个工人。
安装
$ pip install asyncio-throttle
用法
asyncio_throttle.Throttler引入了简单的api: flush()和acquire()。但你不会对那些感兴趣 因为您可以在with语句中使用它,而且看起来更好。
首先,创建给定所需速率限制的节流器。 例如,如果要将速率限制为500/min,可以将其设置为:
fromasyncio_throttleimportThrottlerthrottler=Throttler(rate_limit=500,period=60)
那么每当你想做一些本应有限的工作时 速率(例如,向服务器发送请求),将其放入async with语句:
asyncwiththrottler:send_a_request()
就这么简单。asyncio_throttler很容易集成 与aiohttp一起:
asyncdefworker(throttler,session):whileTrue:asyncwiththrottler:asyncwithsession.get('http://example.com')asresp:do_some_job_with(awaitresp.text())awaitasyncio.sleep(0.05)