diff --git a/weather.py b/weather.py index d2919ca..24326a0 100644 --- a/weather.py +++ b/weather.py @@ -5,6 +5,26 @@ import datetime import dateutil.parser as dp +class NoDefaultLocation(Exception): + def __init__(self, message=None): + default_message = "No default location set" + + if not message: + message = default_message + + super().__init__(message) + + +class NoLocationSpecified(Exception): + def __init__(self, message=None): + default_message = "No location specified" + + if not message: + message = default_message + + super().__init__(message) + + class WeatherApi: def __init__(self, nick): @@ -47,6 +67,11 @@ class WeatherApi: 'units': 'metric' }, } + except KeyError: + user_preferences[nick] = { + 'location': None, + 'units': 'metric' + } return user_preferences @@ -57,20 +82,27 @@ class WeatherApi: if not units or (units and units not in ['metric', 'imperial']): units = 'metric' - user_preferences[nick]['units'] = units + try: + user_preferences[nick]['units'] = units - if location: - user_preferences[nick]['location'] = location + if location: + user_preferences[nick]['location'] = location + + except KeyError: + user_preferences[nick] = { + 'location': location, + 'units': units + } with open(self.user_preferences_filename, 'w') as fp: json.dump(user_preferences, fp) def get_current_conditions(self, nick, location=None, units=None): user_preferences = self.get_user_preferences(nick) - units = user_preferences[nick]['units'] + units = user_preferences[nick]['units'] if nick in user_preferences.keys() else 'metric' if not location: - location = user_preferences[nick]['location'] + location = user_preferences[nick]['location'] if user_preferences[nick]['location'] else raise NoDefaultLocation() # URL for current conditions current_url = f"{self.weather_api_url}/current.json?key={self.api_key}&q={location}&qai=no" @@ -95,13 +127,13 @@ class WeatherApi: def get_forecast(self, nick, location=None, days=5, units=None): user_preferences = self.get_user_preferences(nick) if not units else 'metric' - units = user_preferences[nick]['units'] + units = user_preferences[nick]['units'] if nick in user_preferences.keys() else 'metric' if not location: location = user_preferences[nick]['location'] - # URL for current conditions + # URL for forecast forecast_url = f"{self.weather_api_url}/forecast.json?key={self.api_key}&q={location}&days={days}&qai=no" # Make the request and get the results