1. class TokenCache:
  2. def __init__(self):
  3. self.cache = {} # Dictionary to store tokens and their associated data
  4. def store_token(self, token, data):
  5. """Stores a token and its associated data in the cache."""
  6. self.cache[token] = data
  7. def get_token(self, token):
  8. """Retrieves data associated with a token from the cache."""
  9. return self.cache.get(token)
  10. def remove_token(self, token):
  11. """Removes a token from the cache."""
  12. if token in self.cache:
  13. del self.cache[token]
  14. def clear_cache(self):
  15. """Clears all tokens from the cache."""
  16. self.cache = {}
  17. if __name__ == '__main__':
  18. # Example Usage
  19. cache = TokenCache()
  20. # Simulate obtaining a token
  21. token = "example_token"
  22. data = {"user_id": 123, "expiry": "2024-12-31"}
  23. # Store the token and data
  24. cache.store_token(token, data)
  25. print(f"Token stored: {token}")
  26. # Retrieve the token's data
  27. retrieved_data = cache.get_token(token)
  28. print(f"Retrieved data: {retrieved_data}")
  29. # Remove the token
  30. cache.remove_token(token)
  31. print(f"Token removed: {token}")
  32. # Attempt to retrieve the token again (should return None)
  33. retrieved_data = cache.get_token(token)
  34. print(f"Retrieved data after removal: {retrieved_data}")
  35. #Clear the cache
  36. cache.clear_cache()
  37. print("Cache cleared")

Add your comment