Files
iptv-server/src/utils/database.py

54 lines
1.8 KiB
Python

from upstash_redis import Redis as UpstashRedis
from redis import Redis as LocalRedis, RedisError
import vercel_blob
from src.config import REDIS_URL, REDIS_TOKEN, USE_LOCAL_REDIS, LOCAL_REDIS_URL
from fastapi import HTTPException
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
try:
if USE_LOCAL_REDIS:
redis = LocalRedis.from_url(LOCAL_REDIS_URL)
logger.info("Connecting to local Redis instance...")
else:
if not REDIS_URL or not REDIS_TOKEN:
raise ValueError("Upstash Redis configuration is missing. Please check your environment variables.")
redis = UpstashRedis(
url=REDIS_URL,
token=REDIS_TOKEN
)
logger.info("Connecting to Upstash Redis...")
# Test the connection
redis.ping()
logger.info("Successfully connected to Redis")
except ValueError as ve:
logger.error(f"Configuration error: {str(ve)}")
raise HTTPException(status_code=500, detail="Database configuration error")
except RedisError as re:
logger.error(f"Redis connection error: {str(re)}")
raise HTTPException(status_code=500, detail="Database connection error")
except Exception as e:
logger.error(f"Unexpected error while connecting to Redis: {str(e)}")
raise HTTPException(status_code=500, detail="Internal server error")
def get_blob_by_path(folder: str, filename: str) -> dict:
# Get list of all blobs
resp = vercel_blob.list()
# Search for matching blob path
target_path = f"{folder}/{filename}"
matching_blob = next(
(blob for blob in resp.get('blobs', [])
if blob.get('pathname') == target_path),
None
)
if not matching_blob:
raise HTTPException(status_code=404, detail="File not found")
return matching_blob