Python:检查每个hou的url请求

2024-06-16 12:22:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在访问一个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

Tags: the方法apiidjsonformaturlreturn
2条回答

您可以使用token bucket algorithm,类似这样:http://code.activestate.com/recipes/511490/

以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,因此不需要特别传入第二个参数。在

所以基本上,如果你想让你的脚本每隔一分钟运行一次,你可以这样使用它:

^{pr2}$

如果当前分钟不是偶数,这将停止请求。考虑到这不是最好的方法,可以使用此函数缓存结果(取决于是否允许)。所以基本上,你应该这样做:

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

相关问题 更多 >