#!/usr/bin/env python # -*- coding: utf-8 -*- """ Fix corrupted Redis cache by deleting specific keys """ 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() import redis from conf.env import REDIS_HOST, REDIS_PASSWORD, REDIS_DB def fix_cache(): """Delete corrupted cache keys""" try: # Create Redis connection if REDIS_PASSWORD: r = redis.Redis(host=REDIS_HOST, port=6379, db=REDIS_DB, password=REDIS_PASSWORD) else: r = redis.Redis(host=REDIS_HOST, port=6379, db=REDIS_DB) print("=" * 60) print("Fixing corrupted Redis cache...") print("=" * 60) # List of keys that might be corrupted problem_keys = [ 'init_system_config', 'init_dictionary', ':1:init_system_config', ':1:init_dictionary', ] deleted_count = 0 for key in problem_keys: try: # Try to get the key exists = r.exists(key) if exists: print(f"\n✓ Found key: {key}") # Try to decode it try: value = r.get(key) if value: # Try to decode as UTF-8 value.decode('utf-8') print(f" → Key is OK (can be decoded)") except UnicodeDecodeError: print(f" → Key is CORRUPTED (UTF-8 decode error)") r.delete(key) print(f" → DELETED corrupted key") deleted_count += 1 except Exception as e: print(f" → Error checking key: {e}") r.delete(key) print(f" → DELETED problematic key") deleted_count += 1 except Exception as e: print(f"✗ Error processing key {key}: {e}") # Also clear all keys with pattern print("\n" + "=" * 60) print("Searching for all cache keys...") all_keys = r.keys('*') print(f"Found {len(all_keys)} total keys in Redis DB {REDIS_DB}") if all_keys: print("\nChecking all keys for corruption...") for key in all_keys: try: key_str = key.decode('utf-8') if isinstance(key, bytes) else key value = r.get(key) if value: try: value.decode('utf-8') except UnicodeDecodeError: print(f" → Corrupted key found: {key_str}") r.delete(key) deleted_count += 1 print(f" → DELETED") except Exception as e: print(f" → Error with key: {e}") print("\n" + "=" * 60) print(f"✓ Fixed! Deleted {deleted_count} corrupted keys") print("=" * 60) # Now reinitialize the cache print("\nReinitializing system config...") from application import dispatch dispatch.refresh_system_config() dispatch.refresh_dictionary() print("✓ System config reinitialized!") return True except redis.ConnectionError as e: print(f"✗ Redis connection failed: {e}") print(" Make sure Redis server is running") return False except Exception as e: print(f"✗ Error: {e}") import traceback traceback.print_exc() return False if __name__ == '__main__': fix_cache()