我必须将我的API请求限制为每分钟10次调用,如何修改for循环来完成此操作?
我试图在time.sleep(8)
循环中添加for observation
没有任何运气...任何想法?
import arrow # learn more: https://python.org/pypi/arrow
from WunderWeather import weather # learn more: https://python.org/pypi/WunderWeather
import time
api_key = ''
extractor = weather.Extract(api_key)
zip = '53711'
# get 20170101 00:00
begin_date = arrow.get("2017","YYYY")
# get 20171231 23:00
end_date = arrow.get("2018","YYYY").shift(hours=-1)
for date in arrow.Arrow.range('hour',begin_date,end_date):
# get date object for feature
# http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.weather.Extract.date
date_weather = extractor.date(zip,date.format('YYYYMMDD'))
# use shortcut to get observations and data
# http://wunderweather.readthedocs.io/en/latest/WunderWeather.html#WunderWeather.date.Observation
for observation in date_weather.observations:
time.sleep(8)
print("Date:",observation.date_pretty)
print("Temp:",observation.temp_f)
您仍然超出API限制的原因的可能解释可能与您添加时间等待的行有关。如果您获得的API响应不包含任何观察,则内部循环将不会执行。所以首先我会尝试在API调用之后立即在外循环中等待时间。
你也可以考虑使用像twistedingCall这样的东西来安排你的任务运行每X秒http://twistedmatrix.com/documents/9.0.0/core/howto/time.html
根据您想要数据的实时时间或者您可以承担一天的费用,您可以获得过去日期的所有观察结果,这可能是一次API调用以检索一天的数据(或者它可能是一天的结束当天的观察摘要)。
或者,如果你试图每隔x分钟左右(在极限下)获得当前天气,我会使用某种带有计时器的循环(或者可能是扭曲的,似乎抽象了“循环”)但是打个电话以下之一(取决于您要查找的内容)。您当前的代码正在查找过去的日期,但这些其他端点是当天的日期。
您不希望观察循环中有计时器,因为如上所述,可能没有计时器。
这可以被称为类似于以下示例http://wunderweather.readthedocs.io/en/latest/index.html#additional-examples