From 404126cc70cc1bce2d93c630d792105662de3ee6 Mon Sep 17 00:00:00 2001 From: Mark McIntyre Date: Mon, 19 Sep 2022 07:08:09 -0400 Subject: [PATCH] handled KeyError for user prefs --- weather.py | 20 ++++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/weather.py b/weather.py index d2919ca..ec4b90d 100644 --- a/weather.py +++ b/weather.py @@ -47,6 +47,11 @@ class WeatherApi: 'units': 'metric' }, } + except KeyError: + user_preferences[nick] = { + 'location': None, + 'units': 'metric' + } return user_preferences @@ -57,10 +62,17 @@ 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) @@ -101,7 +113,7 @@ class WeatherApi: 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