1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
5 from builtins import object
12 class SafeHTTPCache(object):
13 """Thread-safe replacement for httplib2.FileCache"""
15 def __init__(self, path=None, max_age=None):
17 if max_age is not None:
19 self._clean(threshold=time.time() - max_age)
23 def _clean(self, threshold=0):
24 for ent in os.listdir(self._dir):
25 fnm = os.path.join(self._dir, ent)
26 if os.path.isdir(fnm) or not fnm.endswith('.tmp'):
29 if stat.st_mtime < threshold:
32 except OSError as err:
33 if err.errno != errno.ENOENT:
39 def _filename(self, url):
40 return os.path.join(self._dir, hashlib.md5(url.encode('utf-8')).hexdigest()+'.tmp')
43 filename = self._filename(url)
45 with open(filename, 'rb') as f:
47 except (IOError, OSError):
50 def set(self, url, content):
52 fd, tempname = tempfile.mkstemp(dir=self._dir)
57 f = os.fdopen(fd, 'wb')
65 os.rename(tempname, self._filename(url))
71 def delete(self, url):
73 os.unlink(self._filename(url))
74 except OSError as err:
75 if err.errno != errno.ENOENT: