| OLD | NEW |
| (Empty) | |
| 1 # Copyright 2016 The Chromium Authors. All rights reserved. |
| 2 # Use of this source code is governed by a BSD-style license that can be |
| 3 # found in the LICENSE file. |
| 4 |
| 5 import logging |
| 6 import os |
| 7 import pickle |
| 8 import threading |
| 9 import zlib |
| 10 |
| 11 from lib.cache_decorator import Cacher |
| 12 |
| 13 CACHE_DIR = os.path.join(os.path.expanduser('~'), '.predator', 'cache') |
| 14 |
| 15 |
| 16 class LocalCacher(Cacher): |
| 17 """Cacher that uses local files to cache data.""" |
| 18 lock = threading.Lock() |
| 19 |
| 20 def __init__(self, cache_dir=CACHE_DIR): |
| 21 self.cache_dir = cache_dir |
| 22 with LocalCacher.lock: |
| 23 if not os.path.exists(cache_dir): # pragma: no cover. |
| 24 os.makedirs(cache_dir) |
| 25 |
| 26 def Get(self, key): |
| 27 with LocalCacher.lock: |
| 28 path = os.path.join(self.cache_dir, key) |
| 29 if not os.path.exists(path): |
| 30 return None |
| 31 |
| 32 try: |
| 33 with open(path) as f: |
| 34 return pickle.loads(zlib.decompress(f.read())) |
| 35 except Exception as error: # pragma: no cover. |
| 36 logging.exception('Failed loading cache: %s', error) |
| 37 return None |
| 38 |
| 39 def Set(self, key, data, expire_time=0): # pylint: disable=W |
| 40 with LocalCacher.lock: |
| 41 try: |
| 42 with open(os.path.join(self.cache_dir, key), 'wb') as f: |
| 43 f.write(zlib.compress(pickle.dumps(data))) |
| 44 except Exception as e: # pragma: no cover. |
| 45 logging.exception('Failed setting cache for key %s: %s', key, e) |
| OLD | NEW |