From 6636a4a0a59dc73cdd4a0e123363794574415df5 Mon Sep 17 00:00:00 2001 From: Starfall Date: Mon, 9 Jan 2023 20:21:10 -0600 Subject: parse cache-control max-age for caching --- meteor.py | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) (limited to 'meteor.py') diff --git a/meteor.py b/meteor.py index 8b7ab2c..140eddb 100755 --- a/meteor.py +++ b/meteor.py @@ -1,7 +1,7 @@ #!/usr/bin/env python3 from argparse import ArgumentParser import requests -import fscache as fs +import fscache base_url = 'https://api.weather.gov' headers = { @@ -50,9 +50,11 @@ def print_forecast(point): try: print(cache.read(cache_key)) - except fs.CacheMiss: - forecast_url = point.get('forecast') - forecast = requests.get(forecast_url, headers=headers).json() + except fscache.CacheMiss: + response = requests.get(point.get('forecast'), headers=headers) + # ugly cache_control parsing honestly, break out later + ttl = int(response.headers['cache-control'].split('max-age=')[-1].split(',')[0]) + forecast = response.json() buffer = f'{term.BOLD}forecast for {point.get("relativeLocation").get("city")}, {point.get("relativeLocation").get("state")} ({cache_key})' buffer += '\n' + f'===================={term.RESET}' @@ -66,13 +68,13 @@ def print_forecast(point): for period in periods[2:]: buffer += '\n' + f'{term.BOLD}{period.get("name").ljust(15)}{term.RESET}: {period.get("shortForecast")} - {period.get("temperature")}°{period.get("temperatureUnit")}, {period.get("windSpeed")} {period.get("windDirection")}' - cache.write(cache_key, buffer) + cache.write(cache_key, buffer, ttl) print(buffer) def main(): args = handle_args() global cache - cache = fs.Cache('meteor.py') + cache = fscache.Cache('meteor.py') point = requests.get(base_url + f'/points/{args.lat},{args.lon}', headers=headers).json() -- cgit