Guest User

Untitled

a guest
Jun 22nd, 2018
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.48 KB | None | 0 0
  1. def _cache_wrapper(func, timeout, unique_arg):
  2. """
  3. :param func: the function that is being decorated
  4. :param timeout: when should the cache time out
  5. :param unique_arg: in case there are too many parameter,
  6. the user can choose to create the hash using one
  7. unique argument instead of many
  8. """
  9. def wrapper(*args, **kwargs):
  10. """
  11. Wrapper that checks the cache if it has anything then
  12. """
  13. # Generate Key given parameters and function name
  14. key = generate_key(args, kwargs, unique_arg, func.__name__)
  15.  
  16. # Get the result from the cache
  17. result = cache.get(key)
  18.  
  19. # Call the function and update the cache if the result is not found
  20. if result is None:
  21. result = func(*args, **kwargs)
  22. cache.set(key, result, timeout)
  23.  
  24. # Open a new thread and check if the cache needs updating
  25. if result is not None:
  26. t = Thread(target=_check_and_update_cache, args=(func, args, kwargs, key,))
  27. t.start()
  28.  
  29. return result
  30.  
  31. return wrapper
  32.  
  33. def cache_output(timeout=60 * 60, unique_arg=None):
  34. """
  35. Decorator function that calls the cache wrapper which handles the generation
  36. of the cache keys, the storage of the function output and the update
  37. mechanism.
  38. """
  39.  
  40. def decorator_function(func):
  41. return _cache_wrapper(func, timeout, unique_arg)
  42.  
  43. return decorator_function
Add Comment
Please, Sign In to add comment