Skip to content

weather["temp_c"] results in KeyError: 'temp_c' #28

@Philbru64

Description

@Philbru64

Every couple of weeks my display goes blank which leads me to turning my pi off and on again to get it going again. I finally made the time to look into the issue when it cropped up again this morning:

The log ends with the following:

File "/home/pi/its-a-plane-python/scenes/weather.py", line 111, in grab_current_temperature
    current_temp = weather["temp_c"]
KeyError: 'temp_c'

In weather.py, grab_weather() loads data in a try block, but I suspect that urllib.request.urlopen() sometimes loads a string which does not contain weather data (eg if there's a server error which returns an error string when an API call is attempted). Therefore it is possible to load invalid data without raising an exception.

My first attempt at solving the problem simply involves referencing the "temp_c" key within the try block:

@lru_cache()
def grab_weather(location, ttl_hash=None):
    del ttl_hash  # not used directly, just part of the cache key

    content = None
    retries = WEATHER_RETRIES

    while retries:
        try:
            request = urllib.request.Request(WEATHER_API_URL + location)
            raw_data = urllib.request.urlopen(request, timeout=3).read()
            content = json.loads(raw_data.decode("utf-8"))
            content["temp_c"] # checking if the retrieved data is valid
            break
        except Exception as e:
            retries -= 1
    else:
        # We've ran out of retries without getting new weather data
        raise WeatherError(
            f"Failed to fetch weather data for '{location}' after {WEATHER_RETRIES} retries"
        )

    return content

My expectation is that this will raise an exception if weather data is not received (which will then trigger a retry). I'll see how it goes in the next few weeks and give feedback.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions