1. import argparse
  2. import os
  3. import json
  4. import time
  5. def invalidate_cache(cache_file, api_endpoints, verbose=False):
  6. """Invalidates the cache for specified API endpoints."""
  7. if not os.path.exists(cache_file):
  8. print(f"Cache file not found: {cache_file}")
  9. return
  10. try:
  11. with open(cache_file, 'r') as f:
  12. cache_data = json.load(f)
  13. except json.JSONDecodeError:
  14. print(f"Error decoding JSON from {cache_file}. Cache file may be corrupted.")
  15. return
  16. if verbose:
  17. print(f"Processing cache file: {cache_file}")
  18. invalidated = False
  19. for endpoint in api_endpoints:
  20. if endpoint in cache_data:
  21. del cache_data[endpoint]
  22. invalidated = True
  23. if verbose:
  24. print(f"Invalidated cache entry for: {endpoint}")
  25. if invalidated:
  26. with open(cache_file, 'w') as f:
  27. json.dump(cache_data, f, indent=4)
  28. print(f"Cache invalidated and saved to: {cache_file}")
  29. else:
  30. print("No cache entries invalidated.")
  31. if __name__ == "__main__":
  32. parser = argparse.ArgumentParser(description="Invalidate API cache.")
  33. parser.add_argument("cache_file", help="Path to the cache file.")
  34. parser.add_argument("endpoints", nargs='+', help="List of API endpoints to invalidate.")
  35. parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output.")
  36. args = parser.parse_args()
  37. invalidate_cache(args.cache_file, args.endpoints, args.verbose)

Add your comment