예제 #1
0
 def _lookup_cache_or_invoke_API(self, cache, API_full_url, timeout):
     cached = cache.get(API_full_url)
     if cached:
         return cached
     else:
         try:
             try:
                 from urllib.request import urlopen
             except ImportError:
                 from urllib2 import urlopen
             response = urlopen(API_full_url, None, timeout)
         except HTTPError as e:
             if '401' in str(e):
                 raise unauthorized_error.UnauthorizedError(
                     'Invalid API key')
             if '404' in str(e):
                 raise not_found_error.NotFoundError(
                     'The resource was not found')
             raise api_call_error.APICallError(str(e), e)
         except URLError as e:
             raise api_call_error.APICallError(str(e), e)
         else:
             data = response.read().decode('utf-8')
             cache.set(API_full_url, data)
             return data
예제 #2
0
 def check_status_code(cls, status_code, payload):
     if status_code < 400:
         return
     if status_code == 400:
         raise api_call_error.APICallError(payload)
     elif status_code == 401:
         raise unauthorized_error.UnauthorizedError(
             'Invalid API Key provided')
     elif status_code == 404:
         raise not_found_error.NotFoundError('Unable to find the resource')
     elif status_code == 502:
         raise api_call_error.BadGatewayError(
             'Unable to contact the upstream server')
     else:
         raise api_call_error.APICallError(payload)
예제 #3
0
def find_closest_weather(weathers_list, unixtime):
    """
    Extracts from the provided list of Weather objects the item which is
    closest in time to the provided UNIXtime.

    :param weathers_list: a list of *Weather* objects
    :type weathers_list: list
    :param unixtime: a UNIX time
    :type unixtime: int
    :returns: the *Weather* object which is closest in time or ``None`` if the
        list is empty
    """
    if not weathers_list:
        return None
    if not is_in_coverage(unixtime, weathers_list):
        raise not_found_error.NotFoundError('Error: the specified time is ' + \
                                'not included in the weather coverage range')
    closest_weather = weathers_list[0]
    time_distance = abs(closest_weather.get_reference_time() - unixtime)
    for weather in weathers_list:
        if abs(weather.get_reference_time() - unixtime) < time_distance:
            time_distance = abs(weather.get_reference_time() - unixtime)
            closest_weather = weather
    return closest_weather