1. import hashlib
  2. import os
  3. import re
  4. from urllib.parse import urlparse
  5. def invalidate_cache(url, staging_envs, cache_dir="cache"):
  6. """
  7. Invalidates the cache for a given URL if it's in a staging environment.
  8. Args:
  9. url (str): The URL of the HTML document.
  10. staging_envs (list): A list of staging environment names (e.g., ["staging", "dev"]).
  11. cache_dir (str): The directory where the cache is stored.
  12. """
  13. if not isinstance(url, str):
  14. raise TypeError("URL must be a string.")
  15. if not isinstance(staging_envs, list):
  16. raise TypeError("staging_envs must be a list.")
  17. if not all(isinstance(env, str) for env in staging_envs):
  18. raise TypeError("All elements in staging_envs must be strings.")
  19. if not os.path.exists(cache_dir):
  20. os.makedirs(cache_dir)
  21. try:
  22. parsed_url = urlparse(url)
  23. filename = parsed_url.path
  24. if not filename:
  25. filename = "index.html" # Default filename
  26. # Generate a hash of the URL for cache key
  27. cache_key = hashlib.md5(filename.encode('utf-8')).hexdigest()
  28. cache_file_path = os.path.join(cache_dir, cache_key)
  29. # Check if the cache file exists
  30. if os.path.exists(cache_file_path):
  31. # Check if the URL is in a staging environment
  32. if any(env in url.lower() for env in staging_envs):
  33. # Invalidate the cache by deleting the file
  34. os.remove(cache_file_path)
  35. print(f"Invalidated cache for: {url}")
  36. else:
  37. print(f"Cache valid for: {url}")
  38. else:
  39. print(f"Cache file not found for: {url}")
  40. except Exception as e:
  41. print(f"Error processing URL {url}: {e}")
  42. if __name__ == '__main__':
  43. #Example Usage
  44. invalidate_cache("https://staging.example.com/index.html", ["staging"])
  45. invalidate_cache("https://dev.example.com/about.html", ["dev"])
  46. invalidate_cache("https://example.com/contact.html", ["staging", "dev"])
  47. invalidate_cache("https://example.com/index.html") #Normal environment
  48. invalidate_cache(123) #Test input validation

Add your comment