我正在访问一个api并提取一个json,但我想确保我的请求不超过每小时一次的限制,最好的方法是什么?在
我在这里提出请求:
# return the json
def returnJSONQuestion(id):
url = 'http://someApi.com?index_id={0}&output=json'
format_url = url.format(id)
try:
urlobject = urllib2.urlopen(format_url)
jsondata = json.loads(urlobject.read().decode("utf-8"))
print jsondata
shortRandomSleep()
except urllib2.URLError, e:
print e.reason
except(json.decoder.JSONDecodeError,ValueError):
print 'Decode JSON has failed'
return jsondata
您可以使用token bucket algorithm,类似这样:http://code.activestate.com/recipes/511490/
以API允许的速率将令牌添加到bucket中,并在每次请求时从bucket中获取令牌。在
我通常使用廉价的黑客程序,通过检查当前时间,每隔一分钟运行一次脚本。这是函数的一般形式:
p
是这里的余数,有一个默认值0
,因此不需要特别传入第二个参数。在所以基本上,如果你想让你的脚本每隔一分钟运行一次,你可以这样使用它:
^{pr2}$如果当前分钟不是偶数,这将停止请求。考虑到这不是最好的方法,可以使用此函数缓存结果(取决于是否允许)。所以基本上,你应该这样做:
相关问题 更多 >
编程相关推荐