def _get_wund_weather(settings, location):
    location = '{},{}'.format(settings['location']['latitude'],
                              settings['location']['longitude'])
    data, cache = _load_cached_data('wund', location)

    if data is None:
        wunderground.set_key(settings['key.wund'])
        data = wunderground.forecast(location)
        cache = _save_cached_data('wund', location, data)

    conditions = data['current_observation']
    weather = {'current': {}, 'forecast': [], 'info': {}}
    weather['info']['time'] = \
        cache['wund']['forecasts'][location]['requested_at']

    weather['current'] = {
        'weather': conditions['weather'],
        'icon': conditions['icon'],
        'humidity': int(conditions['relative_humidity'][:-1])
    }
    if settings['units'] == 'us':
        weather['current']['temp'] = conditions['temp_f']
    else:
        weather['current']['temp'] = conditions['temp_c']

    days = data['forecast']['simpleforecast']['forecastday']
    today = date.today()

    def get_day_info(day):
        d = day['date']
        fdate = date(day=d['day'], month=d['month'], year=d['year'])

        info = {
            'conditions': day['conditions'],
            'precip': day['pop'],
            'icon': day['icon'],
            'date': fdate.strftime('%Y-%m-%d')
        }

        if fdate == today:
            info['day'] = 'Today'
        elif fdate.day - today.day == 1:
            info['day'] = 'Tomorrow'
        else:
            info['day'] = fdate.strftime('%A')

        if settings['units'] == 'us':
            info['temp_hi'] = day['high']['fahrenheit']
            info['temp_lo'] = day['low']['fahrenheit']
        else:
            info['temp_hi'] = day['high']['celsius']
            info['temp_lo'] = day['low']['celsius']

        return info

    forecast = [get_day_info(d) for d in days]
    weather['forecast'] = sorted(forecast, key=lambda d: d['date'])
    return weather
def _get_wund_weather(settings, location):
    location = '{},{}'.format(settings['location']['latitude'],
                              settings['location']['longitude'])
    data, cache = _load_cached_data('wund', location)

    if data is None:
        wunderground.set_key(settings['key.wund'])
        data = wunderground.forecast(location)
        cache = _save_cached_data('wund', location, data)

    conditions = data['current_observation']
    weather = {'current': {}, 'forecast': [], 'info': {}}
    weather['info']['time'] = \
        cache['wund']['forecasts'][location]['requested_at']

    weather['current'] = {
        'weather': conditions['weather'],
        'icon': conditions['icon'],
        'humidity': int(conditions['relative_humidity'][:-1])
    }
    if settings['units'] == 'us':
        weather['current']['temp'] = conditions['temp_f']
    else:
        weather['current']['temp'] = conditions['temp_c']

    days = data['forecast']['simpleforecast']['forecastday']
    today = date.today()

    def get_day_info(day):
        d = day['date']
        fdate = date(day=d['day'], month=d['month'], year=d['year'])

        info = {
            'conditions': day['conditions'],
            'precip': day['pop'],
            'icon': day['icon'],
            'date': fdate.strftime('%Y-%m-%d')
        }

        if fdate == today:
            info['day'] = 'Today'
        elif fdate.day - today.day == 1:
            info['day'] = 'Tomorrow'
        else:
            info['day'] = fdate.strftime('%A')

        if settings['units'] == 'us':
            info['temp_hi'] = day['high']['fahrenheit']
            info['temp_lo'] = day['low']['fahrenheit']
        else:
            info['temp_hi'] = day['high']['celsius']
            info['temp_lo'] = day['low']['celsius']

        return info

    forecast = [get_day_info(d) for d in days]
    weather['forecast'] = sorted(forecast, key=lambda d: d['date'])
    return weather
Esempio n. 3
0
def _get_wund_weather():
    location = '{},{}'.format(settings['location']['latitude'],
                              settings['location']['longitude'])
    data = _load_cached_data('wund', location)

    if data is None:
        wunderground.set_key(settings['key.wund'])
        data = wunderground.forecast(location)
        _save_cached_data('wund', location, data)

    def parse_alert(alert):
        data = {
            'description': alert['description'],
            'expires': datetime.fromtimestamp(int(alert['expires_epoch'])),
        }

        if 'level_meteoalarm' not in alert:
            # only generate URIs for US alerts
            try:
                zone = alert['ZONES'][0]
                data['uri'] = '{}/US/{}/{}.html'.format(SERVICES['wund']['url'],
                                                        zone['state'],
                                                        zone['ZONE'])
            except:
                location = '{},{}'.format(settings['location']['latitude'],
                                          settings['location']['longitude'])
                data['uri'] = wunderground.get_forecast_url(location)
        return data

    weather = {'current': {}, 'forecast': [], 'info': {}}

    if 'alerts' in data:
        weather['alerts'] = [parse_alert(a) for a in data['alerts']]

    conditions = data['current_observation']
    weather['info']['time'] = datetime.strptime(
        cache['wund']['forecasts'][location]['requested_at'], TIMESTAMP_FMT)

    if 'moon_phase' in data:
        def to_time(time_dict):
            hour = int(time_dict['hour'])
            minute = int(time_dict['hour'])
            dt = datetime.now().replace(hour=hour, minute=minute)
            return _localize_time(dt)

        moon_phase = data['moon_phase']
        weather['info']['sunrise'] = to_time(moon_phase['sunrise'])
        weather['info']['sunset'] = to_time(moon_phase['sunset'])

    try:
        r = urlparse.urlparse(conditions['icon_url'])
        parts = os.path.split(r[2])[-1]
        name, ext = os.path.splitext(parts)
        icon = name
    except:
        icon = conditions['icon']


    weather['current'] = {
        'weather': conditions['weather'],
        'icon': icon,
        'humidity': int(conditions['relative_humidity'][:-1])
    }
    if settings['units'] == 'us':
        weather['current']['temp'] = conditions['temp_f']
    else:
        weather['current']['temp'] = conditions['temp_c']

    days = data['forecast']['simpleforecast']['forecastday']

    def get_day_info(day):
        d = day['date']
        fdate = date(day=d['day'], month=d['month'], year=d['year'])

        info = {
            'conditions': day['conditions'],
            'precip': day['pop'],
            'icon': day['icon'],
            'date': fdate
        }

        if settings['units'] == 'us':
            info['temp_hi'] = day['high']['fahrenheit']
            info['temp_lo'] = day['low']['fahrenheit']
        else:
            info['temp_hi'] = day['high']['celsius']
            info['temp_lo'] = day['low']['celsius']

        return info

    forecast = [get_day_info(d) for d in days]
    weather['forecast'] = sorted(forecast, key=lambda d: d['date'])
    return weather
 def test_forecast_Turlock_low(self):
     forecast = wunderground.forecast('Turlock')
     assert_in(
         'low',
         forecast['forecast']['simpleforecast']['forecastday'][0].keys()
     )
Esempio n. 5
0
def condition_forecast(location):
    '''Condition + forecast'''
    # 한국어 위치를 시군 단위의 영어 이름으로 바꾼다. 영어 단어면 바꾸지 않는다.
    transed_location = transloc.translate(location)

    # 위치가 한국어라면
    is_loc_kor = transloc.is_korean(location)

    # 위치가 한국어이며 찾지 못하는 곳이라면
    if is_loc_kor and transed_location == None:
        return '위치({})를 찾을 수 없습니다.'.format(location)

    # 날씨 json을 갱신하고 저장하고 가져온다
    condition_data = wunderground.condition(transed_location,
                                            is_korean=is_loc_kor)

    # Wunderground API가 뻗어있다면 None을 돌려받는다.
    if condition_data is None:
        return '{}, {} {}\n{} {} C {} RH {}\n'.format('', '', '', '', '', '',
                                                      '')

    # 위치가 영어이며 찾지 못하는 곳이라면
    elif type(condition_data) == dict:
        if 'error' in condition_data['response']:
            return 'City Not Found\n\nThe search for "{}" did not return any results.'.format(
                location)

    # 위치를 찾았으며 리스트 결과를 돌려받았다면
    elif 'results' in condition_data['response']:
        new_location = 'zmw:' + condition_data["response"]["results"][0]['zmw']
        condition_data = wunderground.condition(new_location, is_korean=False)
        forecast_data = wunderground.forecast(new_location, is_korean=False)

    else:
        forecast_data = wunderground.forecast(transed_location,
                                              is_korean=is_loc_kor)

    # Condition

    # Full location
    _full_loc = condition_data['current_observation']['display_location'][
        'full']

    cd_co_otr_split = condition_data['current_observation'][
        'observation_time_rfc822'].split(' ')  # Three underscores

    # Day of the week
    try:
        _wd = cd_co_otr_split[0][:-1]
    except Exception as e:
        _wd = ''

    # Day
    try:
        _dd = int(cd_co_otr_split[1])
    except Exception as e:
        _dd = ''

    # Time
    try:
        _time = cd_co_otr_split[4][:5]
    except:
        _time = "error"

    # Weather
    _weat = condition_data['current_observation']['weather']

    # 바로 이전 줄에 표시한 컨디션을 저장한다
    _prev_cond = _weat

    # Rounded Celsius
    def _round(x):
        return int(x + 0.5) if x >= 0 else int(x - 0.5)

    _temp_c = _round(condition_data['current_observation']['temp_c'])

    # Relative humidity
    _rh = condition_data['current_observation']['relative_humidity']

    _ret = '{}, {} {}\n{} {} C {} RH {}\n'.format(_full_loc, _wd, _dd, _time,
                                                  _temp_c, _weat, _rh)

    # Forecast
    try:
        _fcttext_metric = forecast_data['forecast']['txt_forecast'][
            'forecastday'][0]['fcttext_metric']
        _ret += _fcttext_metric
    except Exception as e:
        # loggingmod.logger.warning(e)
        traceback.print_exc()
        # TODO: try-except 없애기

    return _ret
Esempio n. 6
0
    def _get_wund_weather(self):
        LOG.debug('getting weather from Weather Underground')
        location = '{},{}'.format(self.config['location']['latitude'],
                                  self.config['location']['longitude'])
        data = self._load_cached_data('wund', location)

        if data is None:
            wunderground.set_key(self.config['key.wund'])
            data = wunderground.forecast(location)
            self._save_cached_data('wund', location, data)

        def parse_alert(alert):
            data = {'description': alert['description']}
            try:
                data['expires'] = datetime.fromtimestamp(
                    int(alert['expires_epoch']))
            except ValueError:
                data['expires'] = None
                LOG.warn('invalid expiration time: %s', alert['expires_epoch'])

            if 'level_meteoalarm' not in alert:
                # only generate URIs for US alerts
                try:
                    zone = alert['ZONES'][0]
                    data['uri'] = '{}/US/{}/{}.html'.format(
                        SERVICES['wund']['url'], zone['state'], zone['ZONE'])
                except:
                    location = '{},{}'.format(
                        self.config['location']['latitude'],
                        self.config['location']['longitude'])
                    data['uri'] = wunderground.get_forecast_url(location)
            return data

        weather = {'current': {}, 'forecast': [], 'info': {}}

        if 'alerts' in data:
            weather['alerts'] = [parse_alert(a) for a in data['alerts']]

        conditions = data['current_observation']
        weather['info']['time'] = datetime.strptime(
            self.cache['wund']['forecasts'][location]['requested_at'],
            TIMESTAMP_FMT)

        if 'moon_phase' in data:

            def to_time(time_dict):
                hour = int(time_dict['hour'])
                minute = int(time_dict['minute'])
                dt = datetime.now().replace(hour=hour, minute=minute)
                return self._localize_time(dt)

            moon_phase = data['moon_phase']
            weather['info']['sunrise'] = to_time(moon_phase['sunrise'])
            weather['info']['sunset'] = to_time(moon_phase['sunset'])

        try:
            r = urlparse.urlparse(conditions['icon_url'])
            parts = os.path.split(r[2])[-1]
            name, ext = os.path.splitext(parts)
            icon = name
        except:
            icon = conditions['icon']

        feelslike = self.config.get('feelslike', False)

        weather['current'] = {
            'weather': conditions['weather'],
            'icon': icon,
            'humidity': int(conditions['relative_humidity'][:-1])
        }

        temp_kind = 'feelslike' if feelslike else 'temp'

        if self.config['units'] == 'us':
            weather['current']['temp'] = float(conditions[temp_kind + '_f'])
        else:
            weather['current']['temp'] = float(conditions[temp_kind + '_c'])

        days = data['forecast']['simpleforecast']['forecastday']

        def get_day_info(day):
            d = day['date']
            fdate = date(day=d['day'], month=d['month'], year=d['year'])

            info = {
                'conditions': day['conditions'],
                'precip': day['pop'],
                'icon': day['icon'],
                'date': fdate,
            }

            if self.config['units'] == 'us':
                info['temp_hi'] = day['high']['fahrenheit']
                info['temp_lo'] = day['low']['fahrenheit']
            else:
                info['temp_hi'] = day['high']['celsius']
                info['temp_lo'] = day['low']['celsius']

            return info

        forecast = [get_day_info(d) for d in days]
        weather['forecast'] = sorted(forecast, key=lambda d: d['date'])

        weather['forecast'][0]['sunrise'] = self._remotize_time(
            weather['info']['sunrise'])
        weather['forecast'][0]['sunset'] = self._remotize_time(
            weather['info']['sunset'])
        return weather
Esempio n. 7
0
def say_forecast():
  forecast = wunderground.forecast('San Francisco', 'CA')['forecast']
  say('The forecast for today is ' +
      forecast['txt_forecast']['forecastday'][0]['fcttext'])