Пример #1
0
    def get_weather(self):
        owm = OWM(self.api_key)
        weather_mgr = owm.weather_manager()

        city_id_registry = owm.city_id_registry()

        london = city_id_registry.ids_for('London', 'GB')[0][0]

        weather = weather_mgr.weather_at_id(london).weather

        temperature = weather.temperature('celsius')

        forecast = weather_mgr.forecast_at_id(london, '3h', 4).forecast
        forecasts = []

        for hourly_forecast in forecast:
            forecasts.append(
                ForecastInfo(
                    hourly_forecast.reference_time('date'),
                    hourly_forecast.detailed_status,
                    round(hourly_forecast.temperature('celsius')['temp'],
                          1), hourly_forecast.weather_code))

        current_weather = WeatherInfo(london, weather.reference_time('date'),
                                      weather.detailed_status,
                                      round(temperature['temp'], 1),
                                      round(temperature['temp_max'], 1),
                                      round(temperature['temp_min'], 1),
                                      weather.sunrise_time('date'),
                                      weather.sunset_time('date'),
                                      weather.weather_code, forecasts)

        return current_weather
Пример #2
0
class CitySearch:
    def __init__(self):
        self.owm = OWM('246384c9beadbdc4eb18ced4c193e0ae')
        self.reg = self.owm.city_id_registry()
        self.mgr = self.owm.weather_manager()
        self.one_call = None

    def search_city(self, search_word):
        results = self.reg.ids_for(search_word)
        rv_dict = [{
            'text': str(name + ', ' + country)
        } for cityid, name, country in results]
        return rv_dict

    def get_weather_advice(self, city_details, hour_range):
        city_name = city_details[0]
        country_name = city_details[1]
        location = self.reg.locations_for(city_name, country=country_name)
        if isinstance(location, list):
            location = location[0]
        self.one_call = self.mgr.one_call(location.lat, location.lon)
        status_forecast = [
            self.one_call.forecast_hourly[i].status for i in range(hour_range)
        ]
        rain_forecast = [
            self.one_call.forecast_hourly[i].rain for i in range(hour_range)
        ]
        print(status_forecast)
        print(rain_forecast)
        advice = calculate_rain_chance(status_forecast, rain_forecast,
                                       hour_range)
        return advice

    def get_temperatures(self):
        temp_3h = [
            self.one_call.forecast_hourly[i].temperature('celsius')
            for i in range(0, 13, 3)
        ]
        status_3h = [
            self.one_call.forecast_hourly[i].status for i in range(0, 13, 3)
        ]
        icon_paths = []
        for status in status_3h:
            if status == 'Clear':
                icon_paths.append('images\\sun.png')
            elif status == 'Clouds':
                icon_paths.append('images\\clouds.png')
            elif status == 'Rain':
                icon_paths.append('images\\rain.png')
            else:
                icon_paths.append('images\\snow.png')
        print(list(zip(icon_paths, temp_3h)))
        return list(zip(icon_paths, temp_3h))
Пример #3
0
    def execute(self):
        city = self._match.group(1)
        config_dict = get_default_config()
        config_dict['language'] = 'en'
        owm = OWM('6d00d1d4e704068d70191bad2673e0cc', config_dict)
        reg = owm.city_id_registry()

        try:
            mgr = owm.weather_manager()
            observation = mgr.weather_at_place(city)
            #print(observation.location)
            w = re.findall('(\d+.\d+)', str(observation.location))
            lon = float(w[1])
            lat = float(w[2])
        except:
            #проверка на частичное совпадение
            try:
                list_of_tuples = reg.ids_for(city, matching='like')
                city = list_of_tuples[0][1]
            except IndexError:
                print('No object with this name was found\n')
                return ()
            #вывод списка с вариантами
            if len(list_of_tuples) > 1:
                for i in range(0, len(list_of_tuples)):
                    print(i + 1, list_of_tuples[i][1:3])
                #выбор пользователя и проверка
                try:
                    select = int(input('\nSeveral matches were found. Enter a suitable number\n--> '))
                    city_finded = list_of_tuples[select - 1][1]
                    list_of_locations = reg.locations_for(city_finded)
                    city_finded = list_of_locations[0]
                    lat = city_finded.lat
                    lon = city_finded.lon
                    if select < 1:
                        print('Incorrected input\n')
                        return ()
                except:
                    print('Incorrected input\n')
                    return ()

        print('Wait forecast for', city, '...\n')

        one_call = mgr.one_call(lat, lon)
        for i in range(3):
            print(datetime.now().date() + timedelta(days=1 + i))
            print('Wind:', one_call.forecast_daily[i].wind().get('speed', 0), 'm/s\n'
                                                                              'Cloudes:',
                  one_call.forecast_daily[i].detailed_status, '\nDay temperature:',
                  one_call.forecast_daily[i].temperature('celsius').get('feels_like_day', None),
                  'degrees Celsius', '\nNight temperature:',
                  one_call.forecast_daily[i].temperature('celsius').get('feels_like_night',
                                                                        None), "degrees Celsius\n")
def main():
    from time import sleep
    from gpiozero import AngularServo, Button

    owm = OWM('api_key')
    reg = owm.city_id_registry()
    mgr = owm.weather_manager()

    krakow = reg.ids_for('Kraków', country='PL')[0]
    istanbul = reg.ids_for('Istanbul', country='TR')[0]
    stockholm = reg.ids_for('Stockholm', country='SE')[0]

    global btn_state
    btn_state = 0

    CITIES = [krakow, istanbul, stockholm]
    CITY_COUNT = 3
    WEATHER = {
        'clear': -70,
        'mist': -30,
        'haze': -30,
        'smoke': 10,
        'dust': 10,
        'sand': 10,
        'clouds': 10,
        'ash': 10,
        'squall': 10,
        'drizzle': 50,
        'rain': 50,
        'snow': 50,
        'thunderstorm': 50,
        'tornado': 50
    }
    servo1 = AngularServo(17, min_angle=-90, max_angle=90)
    servo1.angle = -90

    def button1_pressed():
        global btn_state
        btn_state += 1
        print("Change to " + str(CITIES[btn_state % CITY_COUNT]))

    button1 = Button(11)
    button1.when_pressed = button1_pressed

    while True:
        weather = mgr.weather_at_id(CITIES[btn_state % CITY_COUNT][0]).weather
        status = str(weather.status).lower()
        servo1.angle = WEATHER.get(status)
        print(str(CITIES[btn_state % CITY_COUNT]) + " : " + status)
        sleep(3)
Пример #5
0
def get_owm_locations_from_text(api: OWM,
                                location: dict) -> List[Tuple[int, str, str]]:
    """
    Gets a list of OWM location tuples from supplied text dictionary of location elements
    """
    if location["type"] != "location":
        log.warn(
            "There is no need to get an OWM location from text for any location that is not "
            "of type 'location'.")
        return None

    # Change the observation type if there is an exclamation mark at the start of the city
    # name so that it only finds accurate names or a star to find any matching names
    search_type = "nocase"
    if location["city"][0:1] == "!":
        search_type = "exact"
        location["city"] = location["city"][1:]
    elif location["city"][0:1] == "*":
        search_type = "like"
        location["city"] = location["city"][1:]

    log.debug("Search type for city '%s' is '%s'", location["city"],
              search_type)
    registry: CityIDRegistry = api.city_id_registry()

    if "country" in location:
        owm_locations = registry.ids_for(city_name=location["city"],
                                         country=location["country"],
                                         matching=search_type)
    else:
        owm_locations = registry.ids_for(city_name=location["city"],
                                         matching=search_type)

    # If DEBUG is turned on
    # https://docs.python.org/3/library/logging.html#levels
    if log.getEffectiveLevel() == 10:
        log.debug("Found %d candidate city ids for name '%s'",
                  len(owm_locations), construct_location_name(location))
        for city_id in owm_locations:
            log.debug("\t %s", city_id)

    return owm_locations
Пример #6
0
def weather(city, radius):
    geo_data = []
    config = get_default_config()
    config['language'] = 'en'
    owm = OWM(KEY, config=config)

    mgr = owm.weather_manager()
    reg = owm.city_id_registry()

    try:
        list_of_geopoints = reg.geopoints_for(f'{city}', country='RU')
        lat = list_of_geopoints[0].lat
        lng = list_of_geopoints[0].lon
        first_temp = mgr.one_call(
            lat=lat, lon=lng).current.temperature('celsius')["temp"]
        cities = parsing.html(lat, lng, radius)
    except:
        return None

    for city in cities:
        try:
            list_of_geopoints = reg.geopoints_for(f'{city}')
            weather = mgr.one_call(lat=list_of_geopoints[0].lat,
                                   lon=list_of_geopoints[0].lon).current
            temp = weather.temperature('celsius')
            if abs(temp["temp"] - first_temp) <= 7:
                geo_data.append([
                    city[0].upper() + city.lower()[1:], temp["temp"],
                    temp["feels_like"] // 1,
                    weather.detailed_status[0].upper() +
                    weather.detailed_status[1:]
                ])
            '''
            print(f'Температура в городе {city[0].upper()+city.lower()[1:]} {temp["temp"]}, ощущается как {temp["feels_like"]//1},\
 {weather.detailed_status}')
            '''
        except:
            pass
    return geo_data
Пример #7
0
from pyowm.owm import OWM
from pyowm.utils.config import get_config_from
from pyowm.utils.config import get_default_config_for_subscription_type
from pyowm.utils import timestamps, formatting

config_dict = get_default_config_for_subscription_type('free')
owm = OWM('1a8b1d6e34be977e469e42517727e81b', config_dict)

owm.supported_languages

config_dict = owm.configuration

version_tuple = (major, minor, patch) = owm.version

reg = owm.city_id_registry()
#list_of_tuples = munich = reg.ids_for('Munich', country='DE')                 # only one: [ (2643743,, 'London, GB') ]
#list_of_tuples = reg.ids_for('london', country='GB', matching='like')           # mehrere Einträge mit bes. string im Namen
#id_of_london_city = list_of_tuples[0][0]

list_of_locations = reg.locations_for('munich', country='DE')
munich = list_of_locations[0]  # IDs als Liste
lat = munich.lat  # Längengrad München
lon = munich.lon  # Breitengrad München

print("city: " + str(list_of_locations))

#print(id_of_london_city)
#print (list_of_tuples[0:5])
#print(lat, lon)

mgr = owm.weather_manager()