akkudoktoreos.core.cache.CacheFileStore

class akkudoktoreos.core.cache.CacheFileStore(*args: Any, **kwargs: Any)

Bases: ConfigMixin, SingletonMixin

A key-value store that manages file-like tempfile objects to be used as cache files.

Cache files are associated with a date. If no date is specified, the cache files are associated with the current date by default. The class provides methods to create new cache files, retrieve existing ones, delete specific files, and clear all cache entries.

CacheFileStore is a thread-safe singleton. Only one store instance will ever be created.

store

A dictionary that holds the in-memory cache file objects with their associated keys and dates.

Type:

dict

Example

>>> cache_store = CacheFileStore()
>>> cache_store.create('example_file')
>>> cache_file = cache_store.get('example_file')
>>> cache_file.write('Some data')
>>> cache_file.seek(0)
>>> print(cache_file.read())  # Output: 'Some data'
__init__(*args: Any, **kwargs: Any) None

Initializes the CacheFileStore instance.

This constructor sets up an empty key-value store (a dictionary) where each key corresponds to a cache file that is associated with a given key and an optional date.

Methods

__init__(*args, **kwargs)

Initializes the CacheFileStore instance.

clear([clear_all, before_datetime])

Deletes all cache files or those expiring before before_datetime.

create(key[, until_date, until_datetime, ...])

Creates a new file-like tempfile object associated with the given key.

current_store()

Current state of the store.

delete(key[, until_date, until_datetime, ...])

Deletes the cache file associated with the given key and datetime.

get(key[, until_date, until_datetime, ...])

Retrieves the cache file associated with the given key and validity datetime.

load_store()

Loads the state of the store from a file.

reset_instance()

Resets the singleton instance, forcing it to be recreated on next access.

save_store()

Saves the current state of the store to a file.

set(key, file_obj[, until_date, ...])

Stores a file-like object in the cache under the specified key and date.

Attributes

config

__init__(*args: Any, **kwargs: Any) None

Initializes the CacheFileStore instance.

This constructor sets up an empty key-value store (a dictionary) where each key corresponds to a cache file that is associated with a given key and an optional date.

create(key: str, until_date: Any | None = None, until_datetime: Any | None = None, with_ttl: Any | None = None, mode: str = 'wb+', delete: bool = False, suffix: str | None = None) IO[bytes]

Creates a new file-like tempfile object associated with the given key.

If a cache file with the given key and valid timedate already exists, the existing file is returned. Otherwise, a new tempfile object is created and stored in the key-value store.

Parameters:
  • key (str) – The key to store the cache file under.

  • until_date (Optional[Any]) – The date until the cache file is valid. Time of day is set to maximum time (23:59:59).

  • until_datetime (Optional[Any]) – The datetime until the cache file is valid. Time of day is set to maximum time (23:59:59) if not provided.

  • with_ttl (Optional[Any]) – The time to live that the cache file is valid. Time starts now.

  • mode (str, optional) – The mode in which the tempfile is opened (e.g., ‘w+’, ‘r+’, ‘wb+’). Defaults to ‘wb+’.

  • delete (bool, optional) – Whether to delete the file after it is closed. Defaults to False (keeps the file).

  • suffix (str, optional) – The suffix for the cache file (e.g., ‘.txt’, ‘.log’). Defaults to None.

Returns:

A file-like object representing the cache file.

Return type:

file_obj

Example

>>> cache_file = cache_store.create('example_file', suffix='.txt')
>>> cache_file.write('Some cached data')
>>> cache_file.seek(0)
>>> print(cache_file.read())  # Output: 'Some cached data'
set(key: str, file_obj: IO[bytes], until_date: Any | None = None, until_datetime: Any | None = None, with_ttl: Any | None = None) None

Stores a file-like object in the cache under the specified key and date.

This method allows you to manually set a file-like object into the cache with a specific key and optional date.

Parameters:
  • key (str) – The key to store the file object under.

  • file_obj – The file-like object.

  • until_date (Optional[Any]) – The date until the cache file is valid. Time of day is set to maximum time (23:59:59).

  • until_datetime (Optional[Any]) – The datetime until the cache file is valid. Time of day is set to maximum time (23:59:59) if not provided.

  • with_ttl (Optional[Any]) – The time to live that the cache file is valid. Time starts now.

Raises:

ValueError – If the key is already in store.

Example

>>> cache_store.set('example_file', io.BytesIO(b'Some binary data'))
get(key: str, until_date: Any | None = None, until_datetime: Any | None = None, at_datetime: Any | None = None, before_datetime: Any | None = None, ttl_duration: Any | None = None) IO[bytes] | None

Retrieves the cache file associated with the given key and validity datetime.

If no cache file is found for the provided key and datetime, the method returns None. The retrieved file is a file-like object that can be read from or written to.

Parameters:
  • key (str) – The key to retrieve the cache file for.

  • until_date (Optional[Any]) – The date until the cache file is valid. Time of day is set to maximum time (23:59:59).

  • until_datetime (Optional[Any]) – The datetime until the cache file is valid. Time of day is set to maximum time (23:59:59) if not provided.

  • at_datetime (Optional[Any]) – The datetime the cache file shall be valid at. Time of day is set to maximum time (23:59:59) if not provided. Defaults to the current datetime if None is provided.

  • before_datetime (Optional[Any]) – The datetime to compare the cache files datetime to be before.

  • ttl_duration (Optional[Any]) – The time to live to compare the cache files time to live to be equal.

Returns:

The file-like cache object, or None if no file is found.

Return type:

file_obj

Example

>>> cache_file = cache_store.get('example_file')
>>> if cache_file:
>>>     cache_file.seek(0)
>>>     print(cache_file.read())  # Output: Cached data (if exists)
delete(key: str, until_date: Any | None = None, until_datetime: Any | None = None, before_datetime: Any | None = None) None

Deletes the cache file associated with the given key and datetime.

This method removes the cache file from the store.

Parameters:
  • key (str) – The key of the cache file to delete.

  • until_date (Optional[Any]) – The date until the cache file is valid. Time of day is set to maximum time (23:59:59).

  • until_datetime (Optional[Any]) – The datetime until the cache file is valid. Time of day is set to maximum time (23:59:59) if not provided.

  • before_datetime (Optional[Any]) – The datetime the cache file shall become or be invalid at. Time of day is set to maximum time (23:59:59) if not provided. Defaults to tommorow start of day.

clear(clear_all: bool | None = None, before_datetime: Any | None = None) None

Deletes all cache files or those expiring before before_datetime.

Parameters:
  • clear_all (bool, optional) – Delete all cache files. Default is False.

  • before_datetime (Optional[Any]) – The threshold date. Cache files that are only valid before this date will be deleted. The default datetime is beginning of today.

Raises:

OSError – If there’s an error during file deletion.

current_store() dict

Current state of the store.

Returns:

current cache management data.

Return type:

data (dict)

save_store() dict

Saves the current state of the store to a file.

Returns:

cache management data that was saved.

Return type:

data (dict)

load_store() dict

Loads the state of the store from a file.

Returns:

cache management data that was loaded.

Return type:

data (dict)

static __new__(cls: Type[SingletonMixin], *args: Any, **kwargs: Any) SingletonMixin

Creates or returns the singleton instance of the class.

Ensures thread-safe instance creation by locking during the first instantiation.

Parameters:
  • *args – Positional arguments for instance creation (ignored if instance exists).

  • **kwargs – Keyword arguments for instance creation (ignored if instance exists).

Returns:

The singleton instance of the derived class.

Return type:

SingletonMixin

config = ConfigEOS(general=GeneralSettings(version='0.2.0', data_folder_path=Path('/home/docs/.local/share/net.akkudoktor.eos'), data_output_subpath=Path('output'), latitude=52.52, longitude=13.405, timezone='Europe/Berlin', data_output_path=Path('/home/docs/.local/share/net.akkudoktor.eos/output'), config_folder_path=Path('/home/docs/.config/net.akkudoktor.eos'), config_file_path=Path('/home/docs/.config/net.akkudoktor.eos/EOS.config.json')), cache=CacheCommonSettings(subpath=Path('cache'), cleanup_interval=300.0), ems=EnergyManagementCommonSettings(startup_delay=5.0, interval=None, mode=None), logging=LoggingCommonSettings(console_level='INFO', file_level=None, file_path=Path('/home/docs/.local/share/net.akkudoktor.eos/output/eos.log')), devices=DevicesCommonSettings(batteries=None, max_batteries=None, electric_vehicles=None, max_electric_vehicles=None, inverters=None, max_inverters=None, home_appliances=None, max_home_appliances=None, measurement_keys=[]), measurement=MeasurementCommonSettings(load_emr_keys=None, grid_export_emr_keys=None, grid_import_emr_keys=None, pv_production_emr_keys=None, keys=[]), optimization=OptimizationCommonSettings(horizon_hours=24, interval=3600, algorithm='GENETIC', genetic=GeneticCommonSettings(individuals=300, generations=400, seed=None, penalties=None)), prediction=PredictionCommonSettings(hours=48, historic_hours=48), elecprice=ElecPriceCommonSettings(provider=None, charges_kwh=None, vat_rate=1.19, provider_settings=ElecPriceCommonProviderSettings(ElecPriceImport=None)), feedintariff=FeedInTariffCommonSettings(provider=None, provider_settings=FeedInTariffCommonProviderSettings(FeedInTariffFixed=None, FeedInTariffImport=None)), load=LoadCommonSettings(provider=None, provider_settings=LoadCommonProviderSettings(LoadAkkudoktor=None, LoadVrm=None, LoadImport=None)), pvforecast=PVForecastCommonSettings(provider=None, provider_settings=PVForecastCommonProviderSettings(PVForecastImport=None, PVForecastVrm=None), planes=None, max_planes=0, planes_peakpower=[], planes_azimuth=[], planes_tilt=[], planes_userhorizon=[], planes_inverter_paco=[]), weather=WeatherCommonSettings(provider=None, provider_settings=WeatherCommonProviderSettings(WeatherImport=None)), server=ServerCommonSettings(host='127.0.0.1', port=8503, verbose=False, startup_eosdash=True, eosdash_host=None, eosdash_port=None), utils=UtilsCommonSettings())
classmethod reset_instance() None

Resets the singleton instance, forcing it to be recreated on next access.