1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
11 class SafeHTTPCache(object):
12 """Thread-safe replacement for httplib2.FileCache"""
14 def __init__(self, path=None, max_age=None):
16 if max_age is not None:
18 self._clean(threshold=time.time() - max_age)
22 def _clean(self, threshold=0):
23 for ent in os.listdir(self._dir):
24 fnm = os.path.join(self._dir, ent)
25 if os.path.isdir(fnm) or not fnm.endswith('.tmp'):
28 if stat.st_mtime < threshold:
31 except OSError as err:
32 if err.errno != errno.ENOENT:
38 def _filename(self, url):
39 return os.path.join(self._dir, hashlib.md5(url.encode('utf-8')).hexdigest()+'.tmp')
42 filename = self._filename(url)
44 with open(filename, 'rb') as f:
46 except (IOError, OSError):
49 def set(self, url, content):
51 fd, tempname = tempfile.mkstemp(dir=self._dir)
56 f = os.fdopen(fd, 'wb')
64 os.rename(tempname, self._filename(url))
70 def delete(self, url):
72 os.unlink(self._filename(url))
73 except OSError as err:
74 if err.errno != errno.ENOENT: