cache_util.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. # pylint: disable=C,R,W
  2. from flask import request
  3. from superset import cache, tables_cache
  4. def view_cache_key(*unused_args, **unused_kwargs):
  5. args_hash = hash(frozenset(request.args.items()))
  6. return 'view/{}/{}'.format(request.path, args_hash)
  7. def default_timeout(*unused_args, **unused_kwargs):
  8. return 5 * 60
  9. def default_enable_cache(*unused_args, **unused_kwargs):
  10. return True
  11. def memoized_func(timeout=default_timeout,
  12. key=view_cache_key,
  13. enable_cache=default_enable_cache,
  14. use_tables_cache=False):
  15. """Use this decorator to cache functions that have predefined first arg.
  16. If enable_cache() is False,
  17. the function will never be cached.
  18. If enable_cache() is True,
  19. cache is adopted and will timeout in timeout() seconds.
  20. If force is True, cache will be refreshed.
  21. memoized_func uses simple_cache and stored the data in memory.
  22. Key is a callable function that takes function arguments and
  23. returns the caching key.
  24. """
  25. def wrap(f):
  26. selected_cache = None
  27. if use_tables_cache and tables_cache:
  28. selected_cache = tables_cache
  29. elif cache:
  30. selected_cache = cache
  31. if selected_cache:
  32. def wrapped_f(cls, *args, **kwargs):
  33. if not enable_cache(*args, **kwargs):
  34. return f(cls, *args, **kwargs)
  35. cache_key = key(*args, **kwargs)
  36. o = selected_cache.get(cache_key)
  37. if not kwargs['force'] and o is not None:
  38. return o
  39. o = f(cls, *args, **kwargs)
  40. selected_cache.set(cache_key, o, timeout=timeout(*args, **kwargs))
  41. return o
  42. else:
  43. # noop
  44. def wrapped_f(cls, *args, **kwargs):
  45. return f(cls, *args, **kwargs)
  46. return wrapped_f
  47. return wrap