#!/usr/bin/env python # -*- coding: utf-8 -*- """ Test Redis connection and clear cache if needed """ import os import sys import django # Setup Django environment sys.path.insert(0, os.path.dirname(__file__)) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings') django.setup() from django.core.cache import cache import redis def test_redis_connection(): """Test if Redis is accessible""" try: from conf.env import REDIS_HOST, REDIS_PASSWORD, REDIS_DB # Create Redis connection if REDIS_PASSWORD: r = redis.Redis(host=REDIS_HOST, port=6379, db=REDIS_DB, password=REDIS_PASSWORD, decode_responses=True) else: r = redis.Redis(host=REDIS_HOST, port=6379, db=REDIS_DB, decode_responses=True) # Test connection response = r.ping() print(f"✓ Redis connection successful: {response}") # Get all keys keys = r.keys('*') print(f"✓ Found {len(keys)} keys in Redis database {REDIS_DB}") if keys: print("\nKeys in Redis:") for key in keys[:10]: # Show first 10 keys print(f" - {key}") if len(keys) > 10: print(f" ... and {len(keys) - 10} more") return True except redis.ConnectionError as e: print(f"✗ Redis connection failed: {e}") print(" Make sure Redis server is running: redis-server") return False except Exception as e: print(f"✗ Error: {e}") return False def clear_django_cache(): """Clear Django cache""" try: cache.clear() print("\n✓ Django cache cleared successfully!") return True except Exception as e: print(f"\n✗ Failed to clear Django cache: {e}") return False if __name__ == '__main__': print("=" * 60) print("Redis Connection Test & Cache Clear Utility") print("=" * 60) if test_redis_connection(): print("\n" + "=" * 60) choice = input("\nDo you want to clear the Django cache? (y/n): ").lower() if choice == 'y': clear_django_cache() else: print("Cache not cleared.") else: print("\n⚠ Cannot clear cache - Redis connection failed") print("Please start Redis server first: redis-server") print("\n" + "=" * 60)