Spaces:
Sleeping
Sleeping
Create Database.py
Browse files- Database.py +112 -0
Database.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import time
|
| 3 |
+
import re
|
| 4 |
+
from app.config import REDIS_URL
|
| 5 |
+
|
| 6 |
+
REDIS_AVAILABLE = False
|
| 7 |
+
try:
|
| 8 |
+
import redis
|
| 9 |
+
REDIS_AVAILABLE = True
|
| 10 |
+
except ImportError:
|
| 11 |
+
print("⚠️ WARNING: 'redis' library not installed. Caching will fall back to local in-memory dictionaries.")
|
| 12 |
+
|
| 13 |
+
# --- SMART STORAGE MEMORY NODE LAYERS ---
|
| 14 |
+
redis_client = None
|
| 15 |
+
IN_MEMORY_CACHE = {}
|
| 16 |
+
IN_MEMORY_EXPIRY = {}
|
| 17 |
+
|
| 18 |
+
if REDIS_AVAILABLE and REDIS_URL:
|
| 19 |
+
try:
|
| 20 |
+
redis_client = redis.Redis.from_url(REDIS_URL, decode_responses=True)
|
| 21 |
+
redis_client.ping()
|
| 22 |
+
print("📶 [Cache Setup] Connected securely to remote Redis server node.")
|
| 23 |
+
except Exception as e:
|
| 24 |
+
print(f"⚠️ [Cache Setup] Redis connection failed ({e}). Defaulting to internal memory arrays.")
|
| 25 |
+
redis_client = None
|
| 26 |
+
|
| 27 |
+
def get_cache_key(product_name: str, size: str = "", mode: str = "balanced") -> str:
|
| 28 |
+
"""Generates a unique deterministic cache key combining name, size, and search mode"""
|
| 29 |
+
clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip())
|
| 30 |
+
clean_size = re.sub(r'[^a-z0-9 ]', '', size.lower().strip()) if size else "nosize"
|
| 31 |
+
clean_name = clean_name.replace(" ", "_")
|
| 32 |
+
clean_size = clean_size.replace(" ", "_")
|
| 33 |
+
return f"tarz:cache:{clean_name}:{clean_size}:{mode}"
|
| 34 |
+
|
| 35 |
+
def get_cached_deals(product_name: str, size: str = "", mode: str = "balanced") -> list:
|
| 36 |
+
"""Retrieves cached pricing data array if available and unexpired"""
|
| 37 |
+
key = get_cache_key(product_name, size, mode)
|
| 38 |
+
if redis_client:
|
| 39 |
+
try:
|
| 40 |
+
data = redis_client.get(key)
|
| 41 |
+
if data: return json.loads(data)
|
| 42 |
+
except Exception as e:
|
| 43 |
+
print(f"⚠️ [Redis Cache Error] Read failed: {e}")
|
| 44 |
+
else:
|
| 45 |
+
if key in IN_MEMORY_CACHE:
|
| 46 |
+
if time.time() < IN_MEMORY_EXPIRY.get(key, 0):
|
| 47 |
+
return IN_MEMORY_CACHE[key]
|
| 48 |
+
else:
|
| 49 |
+
del IN_MEMORY_CACHE[key]
|
| 50 |
+
del IN_MEMORY_EXPIRY[key]
|
| 51 |
+
return None
|
| 52 |
+
|
| 53 |
+
def set_cached_deals(product_name: str, size: str, mode: str, deals: list):
|
| 54 |
+
"""Caches product list matrix with strict 2-hour sliding validation lifetime"""
|
| 55 |
+
if not deals: return
|
| 56 |
+
key = get_cache_key(product_name, size, mode)
|
| 57 |
+
if redis_client:
|
| 58 |
+
try:
|
| 59 |
+
redis_client.setex(key, 7200, json.dumps(deals))
|
| 60 |
+
except Exception as e:
|
| 61 |
+
print(f"⚠️ [Redis Cache Error] Write failed: {e}")
|
| 62 |
+
else:
|
| 63 |
+
IN_MEMORY_CACHE[key] = deals
|
| 64 |
+
IN_MEMORY_EXPIRY[key] = time.time() + 7200
|
| 65 |
+
|
| 66 |
+
def get_base_price(product_name: str, size: str = "", mode: str = "balanced") -> float:
|
| 67 |
+
"""Retrieves the previous cycle's lowest observed stable price benchmark"""
|
| 68 |
+
key = get_cache_key(product_name, size, mode).replace("tarz:cache:", "tarz:baseprice:")
|
| 69 |
+
if redis_client:
|
| 70 |
+
try:
|
| 71 |
+
val = redis_client.get(key)
|
| 72 |
+
if val: return float(val)
|
| 73 |
+
except: pass
|
| 74 |
+
else:
|
| 75 |
+
return IN_MEMORY_CACHE.get(key)
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
def set_base_price(product_name: str, size: str, mode: str, price: float):
|
| 79 |
+
"""Saves a new lowest benchmark configuration when an active shift is confirmed"""
|
| 80 |
+
key = get_cache_key(product_name, size, mode).replace("tarz:cache:", "tarz:baseprice:")
|
| 81 |
+
if redis_client:
|
| 82 |
+
try: redis_client.set(key, str(price))
|
| 83 |
+
except: pass
|
| 84 |
+
else:
|
| 85 |
+
IN_MEMORY_CACHE[key] = price
|
| 86 |
+
|
| 87 |
+
def get_cached_coupons(product_name: str) -> list:
|
| 88 |
+
"""Retrieves isolated promotional matrices matching strict text layout structures"""
|
| 89 |
+
clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip()).replace(" ", "_")
|
| 90 |
+
key = f"tarz:coupons:{clean_name}"
|
| 91 |
+
if redis_client:
|
| 92 |
+
try:
|
| 93 |
+
data = redis_client.get(key)
|
| 94 |
+
if data: return json.loads(data)
|
| 95 |
+
except: pass
|
| 96 |
+
else:
|
| 97 |
+
if key in IN_MEMORY_CACHE:
|
| 98 |
+
if time.time() < IN_MEMORY_EXPIRY.get(key, 0):
|
| 99 |
+
return IN_MEMORY_CACHE[key]
|
| 100 |
+
return None
|
| 101 |
+
|
| 102 |
+
def set_cached_coupons(product_name: str, coupons: list):
|
| 103 |
+
"""Caches discovered active promo strings (saves empty results for 15 mins to prevent loop spam)"""
|
| 104 |
+
clean_name = re.sub(r'[^a-z0-9 ]', '', product_name.lower().strip()).replace(" ", "_")
|
| 105 |
+
key = f"tarz:coupons:{clean_name}"
|
| 106 |
+
duration = 7200 if coupons else 900
|
| 107 |
+
if redis_client:
|
| 108 |
+
try: redis_client.setex(key, duration, json.dumps(coupons))
|
| 109 |
+
except: pass
|
| 110 |
+
else:
|
| 111 |
+
IN_MEMORY_CACHE[key] = coupons
|
| 112 |
+
IN_MEMORY_EXPIRY[key] = time.time() + duration
|