Skip to content

Commit f1899bc

Browse files
authored
Merge pull request #210 from Kl000s/master
Error in how FileSystemCache counts number of files #188
2 parents 82fa1d5 + 908c45a commit f1899bc

File tree

2 files changed

+26
-3
lines changed

2 files changed

+26
-3
lines changed

flask_caching/backends/filesystemcache.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -165,7 +165,7 @@ def get(self, key):
165165
pickle_time = pickle.load(f)
166166
expired = pickle_time != 0 and pickle_time < time()
167167
if expired:
168-
os.remove(filename)
168+
self.delete(key)
169169
else:
170170
hit_or_miss = "hit"
171171
result = pickle.load(f)
@@ -207,6 +207,7 @@ def set(self, key, value, timeout=None, mgmt_element=False):
207207
with os.fdopen(fd, "wb") as f:
208208
pickle.dump(timeout, f, 1)
209209
pickle.dump(value, f, pickle.HIGHEST_PROTOCOL)
210+
is_new_file = not os.path.exists(filename)
210211
os.replace(tmp, filename)
211212
os.chmod(filename, self._mode)
212213
except (IOError, OSError) as exc:
@@ -215,7 +216,7 @@ def set(self, key, value, timeout=None, mgmt_element=False):
215216
result = True
216217
logger.debug("set key %r", key)
217218
# Management elements should not count towards threshold
218-
if not mgmt_element:
219+
if not mgmt_element and is_new_file:
219220
self._update_count(delta=1)
220221
return result
221222

@@ -244,7 +245,7 @@ def has(self, key):
244245
pickle_time = pickle.load(f)
245246
expired = pickle_time != 0 and pickle_time < time()
246247
if expired:
247-
os.remove(filename)
248+
self.delete(key)
248249
else:
249250
result = True
250251
except FileNotFoundError:

tests/test_backend_cache.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,28 @@ def test_no_threshold(self, make_cache):
193193
nof_cache_files = c.get(c._fs_count_file)
194194
assert nof_cache_files is None
195195

196+
def test_filecount_caching_none(self, make_cache):
197+
c = make_cache()
198+
for i in range(3):
199+
assert c.set("a", None)
200+
assert c.get(c._fs_count_file) == 1
201+
202+
def test_filecount_after_deletion_in_has(self, make_cache):
203+
c = make_cache()
204+
assert c.set("foo", "bar", timeout=0.01)
205+
assert c.get(c._fs_count_file) == 1
206+
time.sleep(0.1)
207+
assert c.has("foo") in (False, 0)
208+
assert c.get(c._fs_count_file) == 0
209+
210+
def test_filecount_after_deletion_in_get(self, make_cache):
211+
c = make_cache()
212+
assert c.set("foo", "bar", timeout=0.01)
213+
assert c.get(c._fs_count_file) == 1
214+
time.sleep(0.1)
215+
assert c.get("foo") is None
216+
assert c.get(c._fs_count_file) == 0
217+
196218
def test_count_file_accuracy(self, c):
197219
assert c.set("foo", "bar")
198220
assert c.set("moo", "car")

0 commit comments

Comments
 (0)