Caching
aemetxfb includes an optional, persistent disk cache backed by sqlite3.
It is disabled by default to preserve existing behaviour.
Why cache?
Climate data (normals, extremes, ephemerides) changes infrequently — normals are updated every 10 years, extremes are historical records, and ephemerides are fixed dates. Caching these calls avoids unnecessary network requests and speeds up repeated queries by orders of magnitude.
Enabling the cache
Enable caching via AEMetConfig:
from aemetxfb import AEMetConfig, set_config
set_config(AEMetConfig(cache_enabled=True, cache_ttl=86400))
This enables the cache with a 24-hour TTL. The cache database is stored in
.aemet_cache/ by default.
Using the @cached decorator
Apply cached() to any pure function that returns
pickle-serializable data:
from aemetxfb import AEMetConfig, set_config
from aemetxfb.cache import cached
from aemetxfb.clim import get_normals
set_config(AEMetConfig(cache_enabled=True, cache_ttl=3600))
@cached
def fetch_normals(station: str):
return get_normals(station)
# First call: fetches from AEMet (~0.5s)
df1 = fetch_normals("3129")
# Second call: served from cache (~0.0003s)
df2 = fetch_normals("3129")
Cache key generation
Each unique combination of function name, positional arguments, and keyword arguments produces a distinct cache key (SHA-256 hash). This means:
fetch_normals("3129") # Key A
fetch_normals("B893") # Key B (different station)
fetch_normals("3129") # Key A (served from cache)
Cache management
Query cache statistics:
from aemetxfb.cache import get_cache_stats
stats = get_cache_stats()
print(stats) # {"size": 12288, "entries": 5}
Clear the entire cache:
from aemetxfb.cache import clear_cache
clear_cache()
Manual cache operations
For fine-grained control, use cache_get() and
cache_set():
from aemetxfb.cache import cache_get, cache_set
# Store a value
cache_set("my_key", {"data": [1, 2, 3]})
# Retrieve it
value = cache_get("my_key")
Note
Manual cache_get/cache_set bypasses the @cached decorator and TTL checks.
Use them for custom caching logic.
Cache location
The cache database is stored in the directory specified by cache_dir in
AEMetConfig (default: .aemet_cache/).
set_config(AEMetConfig(
cache_enabled=True,
cache_dir="/tmp/my_cache",
))
You can safely delete the cache directory to start fresh.
What to cache (and what not to)
Cache these:
get_normals()— Updated every 10 years.get_clim_extremes()— Historical records, rarely change.get_clim_ephem()— Fixed dates and events.
Do NOT cache these:
get_last_24h()— Real-time data, changes hourly.get_UVI_previous_day()— Updated daily.get_lightning_latest()— Changes continuously.get_forecast()— Forecasts change every hour.Any function that downloads images or files (
output_pathparameter).