Chromium Code Reviews| Index: appengine/findit/util_scripts/local_cache.py |
| diff --git a/appengine/findit/util_scripts/local_cache.py b/appengine/findit/util_scripts/local_cache.py |
| new file mode 100644 |
| index 0000000000000000000000000000000000000000..2eeeaffff8742d6555156da877bbf138246856ed |
| --- /dev/null |
| +++ b/appengine/findit/util_scripts/local_cache.py |
| @@ -0,0 +1,42 @@ |
| +# Copyright 2015 The Chromium Authors. All rights reserved. |
| +# Use of this source code is governed by a BSD-style license that can be |
| +# found in the LICENSE file. |
| + |
| +import logging |
| +import os |
| +import pickle |
| +import threading |
| +import zlib |
| + |
| +from lib.cache_decorator import Cacher |
| + |
| + |
| +class LocalCacher(Cacher): |
| + """Cacher that uses local files to cache data.""" |
| + lock = threading.Lock() |
| + |
| + def __init__(self, cache_dir): |
| + self.cache_dir = cache_dir |
| + if not os.path.exists(cache_dir): # pragma: no cover. |
|
wrengr
2016/11/11 18:26:26
Again, this sort of code has an inherent race cond
Sharu Jiang
2016/11/12 01:01:50
How about using locks? Or there would be a lot exc
wrengr
2016/11/14 21:48:45
The problem is in (the interaction with) the files
|
| + os.makedirs(cache_dir) |
| + |
| + def Get(self, key): |
| + with LocalCacher.lock: |
| + path = os.path.join(self.cache_dir, key) |
| + if not os.path.exists(path): |
| + return None |
|
wrengr
2016/11/11 18:26:26
You probably want this case to also do the logging
Sharu Jiang
2016/11/12 01:01:50
Done.
Sharu Jiang
2016/11/12 02:00:48
I added back this, for local cacher won't cache fo
|
| + |
| + try: |
| + with open(path) as f: |
| + return pickle.loads(zlib.decompress(f.read())) |
| + except Exception as e: # pragma: no cover. |
| + logging.exception('Failed loading cache: %s', e) |
| + return None |
| + |
| + def Set(self, key, data, expire_time=0): # pylint: disable=W |
| + with LocalCacher.lock: |
| + try: |
| + with open(os.path.join(self.cache_dir, key), 'wb') as f: |
| + f.write(zlib.compress(pickle.dumps(data))) |
| + except Exception as e: # pragma: no cover. |
| + logging.exception('Failed setting cache for key %s: %s', key, e) |