@persistent.persistent_autoloaded_singleton() # type: ignore
-class CachedWeatherData(persistent.Persistent):
+class CachedWeatherData(persistent.PicklingFileBasedPersistent):
def __init__(self, weather_data: Dict[datetime.date, WeatherData] = None):
"""C'tor. Do not pass a dict except for testing purposes.
icon=icon,
)
- @classmethod
+ @staticmethod
@overrides
- def load(cls) -> Any:
+ def get_filename() -> str:
+ return config.config['weather_data_cachefile']
- """Depending on whether we have fresh data persisted either uses that
- data to instantiate the class or makes an HTTP request to fetch the
- necessary data.
-
- Note that because this is a subclass of Persistent this is taken
- care of automatically.
- """
+ @staticmethod
+ @overrides
+ def should_we_save_data(filename: str) -> bool:
+ return True
- if persistent.was_file_written_within_n_seconds(
- config.config['weather_data_cachefile'],
+ @staticmethod
+ @overrides
+ def should_we_load_data(filename: str) -> bool:
+ return persistent.was_file_written_within_n_seconds(
+ filename,
config.config['weather_data_stalest_acceptable'].total_seconds(),
- ):
- import pickle
-
- with open(config.config['weather_data_cachefile'], 'rb') as rf:
- weather_data = pickle.load(rf)
- return cls(weather_data)
- return None
+ )
@overrides
- def save(self) -> bool:
- """
- Saves the current data to disk if required. Again, because this is
- a subclass of Persistent this is taken care of for you.
- """
-
- import pickle
-
- with open(config.config['weather_data_cachefile'], 'wb') as wf:
- pickle.dump(
- self.weather_data,
- wf,
- pickle.HIGHEST_PROTOCOL,
- )
- return True
+ def get_persistent_data(self) -> Any:
+ return self.weather_data