【发布时间】:2014-07-16 22:34:53
【问题描述】:
我想处理 180 个请求/15 分钟的 Search-API 速率限制。我想出的第一个解决方案是检查标头中的剩余请求并等待 900 秒。看下面的sn-p:
results = search_interface.cursor(search_interface.search, q=k, lang=lang, result_type=result_mode)
while True:
try:
tweet = next(results)
if limit_reached(search_interface):
sleep(900)
self.writer(tweet)
def limit_reached(search_interface):
remaining_rate = int(search_interface.get_lastfunction_header('X-Rate-Limit-Remaining'))
return remaining_rate <= 2
但似乎在到达剩余的两个请求后,标头信息并未重置为 180。
我想出的第二个解决方案是处理 twython 异常以限制速率并等待剩余时间:
results = search_interface.cursor(search_interface.search, q=k, lang=lang, result_type=result_mode)
while True:
try:
tweet = next(results)
self.writer(tweet)
except TwythonError as inst:
logger.error(inst.msg)
wait_for_reset(search_interface)
continue
except StopIteration:
break
def wait_for_reset(search_interface):
reset_timestamp = int(search_interface.get_lastfunction_header('X-Rate-Limit-Reset'))
now_timestamp = datetime.now().timestamp()
seconds_offset = 10
t = reset_timestamp - now_timestamp + seconds_offset
logger.info('Waiting {0} seconds for Twitter rate limit reset.'.format(t))
sleep(t)
但是使用此解决方案,我收到此消息 INFO: Resetting dropped connection: api.twitter.com" 并且循环不会继续生成器的最后一个元素。有人遇到过同样的问题吗?
问候。
【问题讨论】:
标签: python python-3.x twitter twython