Skip to content

Commit 3b359fc

Browse files
authored
Simplified cache usage in accounts view helper (#2089)
Importing `cache` instead of `caches` uses the default cache.
1 parent 5afbcb0 commit 3b359fc

File tree

2 files changed

+23
-4
lines changed

2 files changed

+23
-4
lines changed

accounts/tests.py

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,7 @@
1+
import hashlib
2+
13
from django.contrib.auth.models import User
4+
from django.core.cache import cache
25
from django.test import TestCase, override_settings
36
from django_hosts.resolvers import reverse
47

@@ -152,6 +155,23 @@ def test_stat_tickets_triaged_unaccepted_not_counted(self):
152155
response = self.client.get(self.user1_url)
153156
self.assertContains(response, "New tickets triaged: 1.")
154157

158+
@override_settings(
159+
CACHES={
160+
"default": {
161+
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
162+
"LOCATION": "unique-snowflake",
163+
}
164+
}
165+
)
166+
def test_caches_trac_stats(self):
167+
key = "user_vital_status:%s" % hashlib.md5(b"user1").hexdigest()
168+
169+
self.assertIsNone(cache.get(key))
170+
171+
self.client.get(self.user1_url)
172+
173+
self.assertIsNotNone(cache.get(key))
174+
155175

156176
class ViewsTests(TestCase):
157177

accounts/views.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
from django.contrib.auth.decorators import login_required
44
from django.contrib.auth.models import User
5-
from django.core.cache import caches
5+
from django.core.cache import cache
66
from django.shortcuts import get_object_or_404, redirect, render
77

88
from tracdb import stats as trac_stats
@@ -35,16 +35,15 @@ def edit_profile(request):
3535

3636

3737
def get_user_stats(user):
38-
c = caches["default"]
3938
username = user.username.encode("ascii", "ignore")
4039
key = "user_vital_status:%s" % hashlib.md5(username).hexdigest()
41-
info = c.get(key)
40+
info = cache.get(key)
4241
if info is None:
4342
info = trac_stats.get_user_stats(user.username)
4443
# Hide any stat with a value = 0 so that we don't accidentally insult
4544
# non-contributors.
4645
for k, v in list(info.items()):
4746
if v.count == 0:
4847
info.pop(k)
49-
c.set(key, info, 60 * 60)
48+
cache.set(key, info, 60 * 60)
5049
return info

0 commit comments

Comments
 (0)