Skip to content

Commit 825899c

Browse files
committed
Adds simple caching to API calls
Improves performance by caching API responses. The cache stores responses for a configurable TTL.
1 parent 1455e14 commit 825899c

1 file changed

Lines changed: 16 additions & 11 deletions

File tree

pydeepskylog/deepskylog_interface.py

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,12 @@
11
import requests
2+
import time
23

34
DSL_API_BASE_URL = "https://test.deepskylog.org/api/" # Change this as needed
45

6+
# Simple in-memory cache: {url: (timestamp, data)}
7+
_DSL_API_CACHE = {}
8+
_DSL_API_CACHE_TTL = 300 # seconds (5 minutes)
9+
510
def dsl_instruments(username: str) -> dict:
611
"""
712
Get all defined instruments of a DeepskyLog user.
@@ -151,6 +156,15 @@ def _dsl_api_call(api_call: str, username: str) -> dict:
151156
dict: The response from the API call, parsed as a JSON dictionary.
152157
"""
153158
api_url = f"{DSL_API_BASE_URL}{api_call}/{username}"
159+
now = time.time()
160+
161+
# Check cache
162+
cache_entry = _DSL_API_CACHE.get(api_url)
163+
if cache_entry:
164+
timestamp, data = cache_entry
165+
if now - timestamp < _DSL_API_CACHE_TTL:
166+
return data
167+
154168
try:
155169
response = requests.get(api_url, timeout=10)
156170
if response.status_code in (401, 403):
@@ -164,16 +178,6 @@ def _dsl_api_call(api_call: str, username: str) -> dict:
164178
if not isinstance(data, (dict, list)):
165179
raise RuntimeError("Unexpected JSON structure: expected dict or list")
166180

167-
# Example transformation: if data is a list, convert to dict with IDs as keys if possible
168-
if isinstance(data, list):
169-
# Try to use 'id' or 'ID' as key if present
170-
if data and isinstance(data[0], dict) and ('id' in data[0] or 'ID' in data[0]):
171-
key_name = 'id' if 'id' in data[0] else 'ID'
172-
data = {str(item[key_name]): item for item in data if key_name in item}
173-
else:
174-
# Otherwise, return as-is
175-
pass
176-
177181
# Further validation: check for required fields based on api_call
178182
if api_call in ("instrument", "eyepieces", "lenses", "filters"):
179183
if not data:
@@ -182,7 +186,8 @@ def _dsl_api_call(api_call: str, username: str) -> dict:
182186
sample = next(iter(data.values()), None) if isinstance(data, dict) else data[0]
183187
if not isinstance(sample, dict):
184188
raise RuntimeError(f"Malformed data for {api_call}: expected dict entries")
185-
189+
# Store in cache
190+
_DSL_API_CACHE[api_url] = (now, data)
186191
return data
187192

188193
except requests.exceptions.ConnectionError:

0 commit comments

Comments
 (0)