disk.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130
  1. import gzip
  2. from diskcache import FanoutCache, Disk
  3. from diskcache.core import BytesType, MODE_BINARY, BytesIO
  4. from util.logconf import logging
  5. log = logging.getLogger(__name__)
  6. # log.setLevel(logging.WARN)
  7. log.setLevel(logging.INFO)
  8. # log.setLevel(logging.DEBUG)
  9. class GzipDisk(Disk):
  10. def store(self, value, read, key=None):
  11. """
  12. Override from base class diskcache.Disk.
  13. Chunking is due to needing to work on pythons < 2.7.13:
  14. - Issue #27130: In the "zlib" module, fix handling of large buffers
  15. (typically 2 or 4 GiB). Previously, inputs were limited to 2 GiB, and
  16. compression and decompression operations did not properly handle results of
  17. 2 or 4 GiB.
  18. :param value: value to convert
  19. :param bool read: True when value is file-like object
  20. :return: (size, mode, filename, value) tuple for Cache table
  21. """
  22. # pylint: disable=unidiomatic-typecheck
  23. if type(value) is BytesType:
  24. if read:
  25. value = value.read()
  26. read = False
  27. str_io = BytesIO()
  28. gz_file = gzip.GzipFile(mode='wb', compresslevel=1, fileobj=str_io)
  29. for offset in range(0, len(value), 2**30):
  30. gz_file.write(value[offset:offset+2**30])
  31. gz_file.close()
  32. value = str_io.getvalue()
  33. return super(GzipDisk, self).store(value, read)
  34. def fetch(self, mode, filename, value, read):
  35. """
  36. Override from base class diskcache.Disk.
  37. Chunking is due to needing to work on pythons < 2.7.13:
  38. - Issue #27130: In the "zlib" module, fix handling of large buffers
  39. (typically 2 or 4 GiB). Previously, inputs were limited to 2 GiB, and
  40. compression and decompression operations did not properly handle results of
  41. 2 or 4 GiB.
  42. :param int mode: value mode raw, binary, text, or pickle
  43. :param str filename: filename of corresponding value
  44. :param value: database value
  45. :param bool read: when True, return an open file handle
  46. :return: corresponding Python value
  47. """
  48. value = super(GzipDisk, self).fetch(mode, filename, value, read)
  49. if mode == MODE_BINARY:
  50. str_io = BytesIO(value)
  51. gz_file = gzip.GzipFile(mode='rb', fileobj=str_io)
  52. read_csio = BytesIO()
  53. while True:
  54. uncompressed_data = gz_file.read(2**30)
  55. if uncompressed_data:
  56. read_csio.write(uncompressed_data)
  57. else:
  58. break
  59. value = read_csio.getvalue()
  60. return value
  61. def getCache(scope_str):
  62. return FanoutCache('data/cache/' + scope_str, disk=GzipDisk, shards=32, timeout=1, size_limit=2e11)
  63. # def disk_cache(base_path, memsize=2):
  64. # def disk_cache_decorator(f):
  65. # @functools.wraps(f)
  66. # def wrapper(*args, **kwargs):
  67. # args_str = repr(args) + repr(sorted(kwargs.items()))
  68. # file_str = hashlib.md5(args_str.encode('utf8')).hexdigest()
  69. #
  70. # cache_path = os.path.join(base_path, f.__name__, file_str + '.pkl.gz')
  71. #
  72. # if not os.path.exists(os.path.dirname(cache_path)):
  73. # os.makedirs(os.path.dirname(cache_path), exist_ok=True)
  74. #
  75. # if os.path.exists(cache_path):
  76. # return pickle_loadgz(cache_path)
  77. # else:
  78. # ret = f(*args, **kwargs)
  79. # pickle_dumpgz(cache_path, ret)
  80. # return ret
  81. #
  82. # return wrapper
  83. #
  84. # return disk_cache_decorator
  85. #
  86. #
  87. # def pickle_dumpgz(file_path, obj):
  88. # log.debug("Writing {}".format(file_path))
  89. # with open(file_path, 'wb') as file_obj:
  90. # with gzip.GzipFile(mode='wb', compresslevel=1, fileobj=file_obj) as gz_file:
  91. # pickle.dump(obj, gz_file, pickle.HIGHEST_PROTOCOL)
  92. #
  93. #
  94. # def pickle_loadgz(file_path):
  95. # log.debug("Reading {}".format(file_path))
  96. # with open(file_path, 'rb') as file_obj:
  97. # with gzip.GzipFile(mode='rb', fileobj=file_obj) as gz_file:
  98. # return pickle.load(gz_file)
  99. #
  100. #
  101. # def dtpath(dt=None):
  102. # if dt is None:
  103. # dt = datetime.datetime.now()
  104. #
  105. # return str(dt).rsplit('.', 1)[0].replace(' ', '--').replace(':', '.')
  106. #
  107. #
  108. # def safepath(s):
  109. # s = s.replace(' ', '_')
  110. # return re.sub('[^A-Za-z0-9_.-]', '', s)