API速率限制修饰符
ratelimit的Python项目详细描述
api是与web服务交互的一种非常常见的方式。根据需要 消耗数据的数量在增长,保持 数据源的日期。然而,许多api提供者限制开发人员 调用太多的api。这就是所谓的限速,在最坏的情况下 假设您的应用程序可以被禁止进行进一步的api调用 滥用这些限制。
这个包引入了一个函数装饰器来防止函数 调用的频率高于api提供程序所允许的频率。这应该可以防止 API供应商不得通过遵守其费率来禁止您的应用程序 限制。
安装
Pypi
要安装RateLimit,只需:
$ pip install ratelimit
Github
从github安装最新版本:
$ git clone https://github.com/tomasbasham/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
贡献
- 分叉(https://github.com/tomasbasham/ratelimit/fork)
- 创建您的功能分支(git checkout-b my new feature)
- 提交更改(git commit-am'add some feature')
- 推到分支(git push origin my new feature)
- 创建新的拉取请求