import httpx import os import redis from dotenv import load_dotenv # Load environment variables load_dotenv() # Redis connection setup using environment variables redis_client = redis.Redis( host=os.getenv('REDIS_HOST', 'localhost'), port=int(os.getenv('REDIS_PORT', 6379)), password=os.getenv('REDIS_PASSWORD', None), ssl=os.getenv('REDIS_SSL', 'False').lower() == 'true' ) TMDB_POSTER_URL = 'https://image.tmdb.org/t/p/w500' TMDB_BACK_URL = 'https://image.tmdb.org/t/p/original' TMDB_API_KEY = os.getenv('TMDB_API_KEY') CACHE_EXPIRE_TIME = 43200 # 12 hours async def get_tmdb_data(client: httpx.AsyncClient, imdb_id: str, language: str = "it") -> dict: # Generate a unique Redis key for each movie and language combination cache_key = f"tmdb:{imdb_id}:{language}" # Attempt to fetch data from Redis cache cached_data = redis_client.get(cache_key) if cached_data: # If data is cached, decode it from bytes to dictionary return eval(cached_data.decode("utf-8")) # If not cached, fetch data from TMDB API url = f"https://api.themoviedb.org/3/find/{imdb_id}" params = { "external_source": "imdb_id", "language": language, "api_key": TMDB_API_KEY } headers = { "accept": "application/json" } response = await client.get(url, headers=headers, params=params) # Cache the data if the request is successful if response.status_code == 200: data = response.json() # Store the data in Redis with an expiration time, convert dict to string for storage redis_client.setex(cache_key, CACHE_EXPIRE_TIME, str(data)) return data else: return {} # Return empty dict if the request fails