API速率限制修饰符
deckar01-ratelimit的Python项目详细描述
这个项目是tomasbasham/ratelimit的分支 实现sliding log 为了正确性,并通过sqlite提供持久性。请参阅上的“用法”部分 Persistence了解更多详细信息。开启持久性是非常重要的 建议,尤其是在开发期间,以确保遵守费率限制 在应用程序重新启动之间。在
api是与web服务交互的一种非常常见的方式。因为需要 消费数据不断增长,需要保持在 数据源的日期。然而,许多API提供者限制开发人员 进行太多API调用。这就是所谓的速率限制,在最坏的情况下 如果可以禁止应用程序进一步调用API 滥用这些限制。在
这个包引入了一个函数修饰符来防止函数 调用频率超过API提供程序允许的次数。这应该可以防止 API供应商禁止你的应用程序通过遵守他们的费率 限制。在
安装
PyPi
将此行添加到应用程序的要求.txt公司名称:
deckar01-ratelimit
然后执行:
^{pr2}$或者自己安装:
$ pip install deckar01-ratelimit
GitHub
从Github安装最新版本:
$ git clone https://github.com/deckar01/ratelimit
$ cd ratelimit
$ python setup.py install
使用
要使用此包,只需装饰任何进行API调用的函数:
fromratelimitimportlimitsimportrequestsFIFTEEN_MINUTES=900@limits(calls=15,period=FIFTEEN_MINUTES)defcall_api(url):response=requests.get(url)ifresponse.status_code!=200:raiseException('API response: {}'.format(response.status_code))returnresponse
此函数将无法在15分钟内进行超过15次的API调用 时间段。在
传入decorator的参数描述函数的数量 允许在指定的时间段(以秒为单位)进行调用。如果没有时间段 则默认为15分钟(由 推特)。在
如果一个修饰函数被调用的次数超过了 指定时间段,则引发ratelimit.RateLimitException。这个 可用于实现重试策略,如expoential backoff
fromratelimitimportlimits,RateLimitExceptionfrombackoffimporton_exception,expoimportrequestsFIFTEEN_MINUTES=900@on_exception(expo,RateLimitException,max_tries=8)@limits(calls=15,period=FIFTEEN_MINUTES)defcall_api(url):response=requests.get(url)ifresponse.status_code!=200:raiseException('API response: {}'.format(response.status_code))returnresponse
或者使当前线程休眠到指定的时间 句点已结束,然后使用^{tt2}重试函数$ 装饰工。这样可以确保在 停止线程的成本。在
fromratelimitimportlimits,sleep_and_retryimportrequestsFIFTEEN_MINUTES=900@sleep_and_retry@limits(calls=15,period=FIFTEEN_MINUTES)defcall_api(url):response=requests.get(url)ifresponse.status_code!=200:raiseException('API response: {}'.format(response.status_code))returnresponse
持续性
如果在应用程序重新启动或共享之间需要遵守限制 在多个进程中,storage参数可用于保存限制 状态到磁盘并自动加载。在
fromratelimitimportlimits,sleep_a_retryimportrequestsFIFTEEN_MINUTES=900@sleep_and_retry@limits(calls=15,period=FIFTEEN_MINUTES,storage='ratelimit.db')defcall_api(url):response=requests.get(url)ifresponse.status_code!=200:raiseException('API response: {}'.format(response.status_code))returnresponse
如果需要持久化多个限制,name参数可用于 使用不同的表将它们存储在同一个数据库中。在
fromratelimitimportlimits,sleep_a_retryimportrequestsHOUR=3600DAY=24*HOUR@sleep_and_retry@limits(calls=15,period=HOUR,storage='ratelimit.db',name='hourly_limit')@sleep_and_retry@limits(calls=100,period=DAY,storage='ratelimit.db',name='daily_limit')defcall_api(url):response=requests.get(url)ifresponse.status_code!=200:raiseException('API response: {}'.format(response.status_code))returnresponse
许可证
{a5}是这个项目的许可证。在
- 项目
标签: