orion-cache 0.1.0__tar.gz

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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ali Rashidi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: orion-cache
3
+ Version: 0.1.0
4
+ Summary: Shared Redis cache decorator for internal Python services — write once, import everywhere.
5
+ Author-email: Ali Rashidi <aliinreallifee@gmail.com>
6
+ License: MIT
7
+ Project-URL: Repository, https://github.com/aliinreallife/orion-cache
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: redis>=5.0.0
12
+ Requires-Dist: python-dotenv>=1.0.0
13
+ Dynamic: license-file
14
+
15
+ # orion-cache
16
+ orion-cache Shared Redis cache decorator for internal Python services — write once, import everywhere.
@@ -0,0 +1,2 @@
1
+ # orion-cache
2
+ orion-cache Shared Redis cache decorator for internal Python services — write once, import everywhere.
@@ -0,0 +1,3 @@
1
+ from .cache import redis_cache, clear_all_caches, get_client
2
+
3
+ __all__ = ["redis_cache", "clear_all_caches", "get_client"]
@@ -0,0 +1,80 @@
1
+ import json
2
+ import logging
3
+ import functools
4
+ from typing import Callable, Any
5
+
6
+ import redis
7
+
8
+ from .config import REDIS_URL, DEFAULT_TTL
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ _client: redis.Redis | None = None
13
+
14
+
15
+ def get_client() -> redis.Redis:
16
+ """Returns a singleton Redis client."""
17
+ global _client
18
+ if _client is None:
19
+ _client = redis.from_url(REDIS_URL, decode_responses=True, socket_timeout=2)
20
+ return _client
21
+
22
+
23
+ def redis_cache(ttl: int = DEFAULT_TTL) -> Callable:
24
+ """
25
+ Decorator that caches a function's return value in Redis.
26
+
27
+ Usage:
28
+ @redis_cache(ttl=120)
29
+ def get_orders(customer):
30
+ return db.query(...)
31
+ """
32
+ def decorator(func: Callable) -> Callable:
33
+ @functools.wraps(func)
34
+ def wrapper(*args, **kwargs) -> Any:
35
+ key = f"{func.__name__}:{args}:{kwargs}"
36
+ client = get_client()
37
+
38
+ try:
39
+ cached = client.get(key)
40
+ if cached is not None:
41
+ logger.debug("Cache HIT: %s", key)
42
+ return json.loads(cached)
43
+ except redis.RedisError as e:
44
+ logger.warning("Cache read failed, falling through to function. Error: %s", e)
45
+
46
+ logger.debug("Cache MISS: %s", key)
47
+ result = func(*args, **kwargs)
48
+
49
+ try:
50
+ client.setex(key, ttl, json.dumps(result, default=str))
51
+ except redis.RedisError as e:
52
+ logger.warning("Cache write failed. Error: %s", e)
53
+
54
+ return result
55
+ return wrapper
56
+ return decorator
57
+
58
+
59
+ def clear_all_caches(pattern: str = "*") -> int:
60
+ """
61
+ Deletes all keys matching the given pattern.
62
+ Defaults to clearing everything. Use a pattern like 'get_orders:*' to be selective.
63
+ Returns number of deleted keys.
64
+ """
65
+ client = get_client()
66
+ try:
67
+ cursor = 0
68
+ deleted = 0
69
+ while True:
70
+ cursor, keys = client.scan(cursor, match=pattern, count=100)
71
+ if keys:
72
+ client.delete(*keys)
73
+ deleted += len(keys)
74
+ if cursor == 0:
75
+ break
76
+ logger.info("Cleared %d cache keys (pattern: %s)", deleted, pattern)
77
+ return deleted
78
+ except redis.RedisError as e:
79
+ logger.error("Cache clear failed. Error: %s", e)
80
+ return 0
@@ -0,0 +1,17 @@
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ load_dotenv() # loads .env file if present, ignored in prod where real env vars are set
5
+
6
+ REDIS_HOST = os.getenv("REDIS_HOST", "localhost")
7
+ REDIS_PORT = int(os.getenv("REDIS_PORT", 6379))
8
+ REDIS_PASSWORD = os.getenv("REDIS_PASSWORD", None)
9
+ REDIS_DB = int(os.getenv("REDIS_DB", 0))
10
+ DEFAULT_TTL = int(os.getenv("CACHE_DEFAULT_TTL", 300))
11
+
12
+ REDIS_URL = os.getenv(
13
+ "REDIS_URL",
14
+ f"redis://:{REDIS_PASSWORD}@{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}"
15
+ if REDIS_PASSWORD
16
+ else f"redis://{REDIS_HOST}:{REDIS_PORT}/{REDIS_DB}",
17
+ )
@@ -0,0 +1,16 @@
1
+ Metadata-Version: 2.4
2
+ Name: orion-cache
3
+ Version: 0.1.0
4
+ Summary: Shared Redis cache decorator for internal Python services — write once, import everywhere.
5
+ Author-email: Ali Rashidi <aliinreallifee@gmail.com>
6
+ License: MIT
7
+ Project-URL: Repository, https://github.com/aliinreallife/orion-cache
8
+ Requires-Python: >=3.9
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: redis>=5.0.0
12
+ Requires-Dist: python-dotenv>=1.0.0
13
+ Dynamic: license-file
14
+
15
+ # orion-cache
16
+ orion-cache Shared Redis cache decorator for internal Python services — write once, import everywhere.
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ orion_cache/__init__.py
5
+ orion_cache/cache.py
6
+ orion_cache/config.py
7
+ orion_cache.egg-info/PKG-INFO
8
+ orion_cache.egg-info/SOURCES.txt
9
+ orion_cache.egg-info/dependency_links.txt
10
+ orion_cache.egg-info/requires.txt
11
+ orion_cache.egg-info/top_level.txt
12
+ tests/test_cache.py
@@ -0,0 +1,2 @@
1
+ redis>=5.0.0
2
+ python-dotenv>=1.0.0
@@ -0,0 +1 @@
1
+ orion_cache
@@ -0,0 +1,16 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "orion-cache"
7
+ version = "0.1.0"
8
+ description = "Shared Redis cache decorator for internal Python services — write once, import everywhere."
9
+ authors = [{ name = "Ali Rashidi", email = "aliinreallifee@gmail.com" }]
10
+ license = { text = "MIT" }
11
+ readme = "README.md"
12
+ requires-python = ">=3.9"
13
+ dependencies = ["redis>=5.0.0", "python-dotenv>=1.0.0"]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/aliinreallife/orion-cache"
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,30 @@
1
+ from unittest.mock import patch, MagicMock
2
+ from orion_cache import redis_cache
3
+
4
+
5
+ def test_cache_miss_then_hit():
6
+ mock_client = MagicMock()
7
+ mock_client.get.return_value = None # first call is a miss
8
+
9
+ with patch("orion_cache.cache.get_client", return_value=mock_client):
10
+ @redis_cache(ttl=60)
11
+ def get_data(name):
12
+ return {"name": name}
13
+
14
+ result = get_data("ali")
15
+ assert result == {"name": "ali"}
16
+ mock_client.setex.assert_called_once()
17
+
18
+
19
+ def test_cache_hit_returns_cached():
20
+ import json
21
+ mock_client = MagicMock()
22
+ mock_client.get.return_value = json.dumps({"name": "ali"})
23
+
24
+ with patch("orion_cache.cache.get_client", return_value=mock_client):
25
+ @redis_cache(ttl=60)
26
+ def get_data(name):
27
+ raise Exception("should not be called")
28
+
29
+ result = get_data("ali")
30
+ assert result == {"name": "ali"}