2012-09-12 2 views
1

api에 액세스하고 json을 추출 중이지만 시간 제한 요청 제한 내에 머물러 있는지 확인하려면이 작업을 수행하는 가장 좋은 방법은 무엇입니까? 내가 요청하기Python : 시간당 URL 요청을 확인하십시오.

이 : 당신은 token bucket algorithm을 사용할 수

# 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 

답변

1

나는 보통 스크립트를 현재 시간을 확인하여 매 분마다 실행하도록하는 값싼 해킹을 사용합니다. 이 함수의 일반적인 형식입니다

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