opensky-cli 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
opensky/cache.py ADDED
@@ -0,0 +1,49 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import json
5
+ from pathlib import Path
6
+ from typing import Any
7
+
8
+ import diskcache
9
+
10
+ _CACHE_DIR = Path.home() / ".cache" / "opensky" / "searches"
11
+ _DEFAULT_TTL = 3600 # 1 hour
12
+
13
+ _cache: diskcache.Cache | None = None
14
+
15
+
16
+ def _get_cache() -> diskcache.Cache:
17
+ global _cache
18
+ if _cache is None:
19
+ _cache = diskcache.Cache(str(_CACHE_DIR))
20
+ return _cache
21
+
22
+
23
+ def cache_key(origin: str, dest: str, date: str, **params: Any) -> str:
24
+ parts = f"{origin}-{dest}-{date}"
25
+ if params:
26
+ parts += "-" + json.dumps(params, sort_keys=True, separators=(",", ":"))
27
+ return hashlib.sha256(parts.encode()).hexdigest()[:16]
28
+
29
+
30
+ def get(key: str) -> Any | None:
31
+ return _get_cache().get(key)
32
+
33
+
34
+ def put(key: str, value: Any, ttl: int = _DEFAULT_TTL) -> None:
35
+ _get_cache().set(key, value, expire=ttl)
36
+
37
+
38
+ def clear() -> None:
39
+ c = _get_cache()
40
+ c.clear()
41
+
42
+
43
+ def stats() -> dict[str, Any]:
44
+ c = _get_cache()
45
+ return {
46
+ "size": len(c),
47
+ "directory": str(_CACHE_DIR),
48
+ "volume": c.volume(),
49
+ }