Skip to content

Commit

Permalink
Fixed bug in cached_model_property caused cache to last forever
Browse files Browse the repository at this point in the history
  • Loading branch information
ramast committed Feb 16, 2016
1 parent dfd4971 commit 68c8281
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 3 deletions.
7 changes: 5 additions & 2 deletions model_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ def get_x(obj):
# If not cached, call the actual method and cache the result
if result is None:
result = f(obj)
cache.set(cache_key, result, cache_timeout)
set_x(obj, result)
return result

def del_x(obj):
Expand All @@ -166,7 +166,10 @@ def set_x(obj, value):
"""
cache_key = _get_cache_key(obj)
# Save that key in the cache
cache.set(cache_key, value, cache_timeout)
if cache_timeout is None:
cache.set(cache_key, value)
else:
cache.set(cache_key, value, cache_timeout)

if readonly:
return property(fget=get_x, fdel=del_x)
Expand Down
2 changes: 1 addition & 1 deletion tests/simple_app/simple_app/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
'default': {
'BACKEND': 'django.core.cache.backends.db.DatabaseCache',
'LOCATION': 'cache',
'TIMEOUT': 1200 # Every 20 Minute
'TIMEOUT': 3 # Every 3 seconds
}
}

Expand Down
8 changes: 8 additions & 0 deletions tests/test_cached_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,3 +62,11 @@ def test_cache_timeout():
sleep(2)
tools.assert_equal(team.one_sec_cache, 2)
tools.assert_equal(team.one_sec_cache, 2)

# test default cache timeout (we set it to 3 seconds)
team = Team(name="Team1")
del team.cached_counter
tools.assert_equal(team.cached_counter, 1)
tools.assert_equal(team.cached_counter, 1)
sleep(4)
tools.assert_equal(team.cached_counter, 2)

0 comments on commit 68c8281

Please sign in to comment.