Python:每小时检查url请求
我正在访问一个api并提取一个json,但我想确保我保持在每小时请求的限制内,这样做的最佳方式是什么 我在此提出请求:Python:每小时检查url请求,python,time,urlrequest,Python,Time,Urlrequest,我正在访问一个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_
# 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
你可以用一个,类似这样的:
以API允许您发出请求的速率将令牌添加到bucket中,并在每次发出请求时从bucket中获取令牌。我通常使用一种便宜的方法,通过检查当前时间每隔一分钟运行一次脚本。这是函数的一般形式:
def minuteMod(x, p=0):
import datetime
minute = datetime.datetime.now() + datetime.timedelta(seconds=15)
minute = int(datetime.datetime.strftime(minute, "%M"))
if minute % x == p:
return True
return False
p
是此处的余数,其默认值为0
,因此无需特别传入第二个参数
因此,基本上,如果希望脚本每隔一分钟运行一次,可以这样使用:
def returnJSONQuestion(id):
if not minuteMod(2):
return None or ''
# rest of the code
def returnJSONQuestion(id):
if minuteMod(3): # current minute is a factor of 3
return jsonFromCache # open a file and output cached contents
else:
url = 'http://...'
storeJSONToFile(url)
return json
如果当前分钟数不相等,则此操作将停止请求。考虑到这不是最好的方法,您可以使用此函数缓存结果(取决于是否允许)。所以基本上,你会这样做:
def returnJSONQuestion(id):
if not minuteMod(2):
return None or ''
# rest of the code
def returnJSONQuestion(id):
if minuteMod(3): # current minute is a factor of 3
return jsonFromCache # open a file and output cached contents
else:
url = 'http://...'
storeJSONToFile(url)
return json