cache.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. # Licensed to the Apache Software Foundation (ASF) under one
  2. # or more contributor license agreements. See the NOTICE file
  3. # distributed with this work for additional information
  4. # regarding copyright ownership. The ASF licenses this file
  5. # to you under the Apache License, Version 2.0 (the
  6. # "License"); you may not use this file except in compliance
  7. # with the License. You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing,
  12. # software distributed under the License is distributed on an
  13. # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14. # KIND, either express or implied. See the License for the
  15. # specific language governing permissions and limitations
  16. # under the License.
  17. from flask import request
  18. from superset.extensions import cache_manager
  19. def view_cache_key(*_, **__) -> str:
  20. args_hash = hash(frozenset(request.args.items()))
  21. return "view/{}/{}".format(request.path, args_hash)
  22. def memoized_func(key=view_cache_key, attribute_in_key=None):
  23. """Use this decorator to cache functions that have predefined first arg.
  24. enable_cache is treated as True by default,
  25. except enable_cache = False is passed to the decorated function.
  26. force means whether to force refresh the cache and is treated as False by default,
  27. except force = True is passed to the decorated function.
  28. timeout of cache is set to 600 seconds by default,
  29. except cache_timeout = {timeout in seconds} is passed to the decorated function.
  30. memoized_func uses simple_cache and stored the data in memory.
  31. Key is a callable function that takes function arguments and
  32. returns the caching key.
  33. """
  34. def wrap(f):
  35. if cache_manager.tables_cache:
  36. def wrapped_f(self, *args, **kwargs):
  37. if not kwargs.get("cache", True):
  38. return f(self, *args, **kwargs)
  39. if attribute_in_key:
  40. cache_key = key(*args, **kwargs).format(
  41. getattr(self, attribute_in_key)
  42. )
  43. else:
  44. cache_key = key(*args, **kwargs)
  45. o = cache_manager.tables_cache.get(cache_key)
  46. if not kwargs.get("force") and o is not None:
  47. return o
  48. o = f(self, *args, **kwargs)
  49. cache_manager.tables_cache.set(
  50. cache_key, o, timeout=kwargs.get("cache_timeout")
  51. )
  52. return o
  53. else:
  54. # noop
  55. def wrapped_f(self, *args, **kwargs):
  56. return f(self, *args, **kwargs)
  57. return wrapped_f
  58. return wrap