Skip to content

Commit a493397

Browse files
julienc91agateblue
authored andcommitted
Optimize cache update by batch
1 parent d6cfbb6 commit a493397

File tree

1 file changed

+20
-11
lines changed

1 file changed

+20
-11
lines changed

dynamic_preferences/managers.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -104,18 +104,22 @@ def many_from_cache(self, preferences):
104104
if k in cached
105105
}
106106

107-
def to_cache(self, pref):
107+
def to_cache(self, *prefs):
108108
"""
109-
Update/create the cache value for the given preference model instance
109+
Update/create the cache value for the given preference model instances
110110
"""
111-
key = self.get_cache_key(pref.section, pref.name)
112-
value = pref.raw_value
113-
if value is None or value == "":
114-
# some cache backends refuse to cache None or empty values
115-
# resulting in more DB queries, so we cache an arbitrary value
116-
# to ensure the cache is hot (even with empty values)
117-
value = preferences_settings.CACHE_NONE_VALUE
118-
self.cache.set(key, value)
111+
update_dict = {}
112+
for pref in prefs:
113+
key = self.get_cache_key(pref.section, pref.name)
114+
value = pref.raw_value
115+
if value is None or value == "":
116+
# some cache backends refuse to cache None or empty values
117+
# resulting in more DB queries, so we cache an arbitrary value
118+
# to ensure the cache is hot (even with empty values)
119+
value = preferences_settings.CACHE_NONE_VALUE
120+
update_dict[key] = value
121+
122+
self.cache.set_many(update_dict)
119123

120124
def pref_obj(self, section, name):
121125
return self.registry.get(section=section, name=name)
@@ -220,6 +224,8 @@ def load_from_db(self, cache=False):
220224
"""Return a dictionary of preferences by section directly from DB"""
221225
a = {}
222226
db_prefs = {p.preference.identifier(): p for p in self.queryset}
227+
cache_prefs = []
228+
223229
for preference in self.registry.preferences():
224230
try:
225231
db_pref = db_prefs[preference.identifier()]
@@ -232,8 +238,11 @@ def load_from_db(self, cache=False):
232238
else:
233239
# cache if create_db_pref() hasn't already done so
234240
if cache:
235-
self.to_cache(db_pref)
241+
cache_prefs.append(db_pref)
236242

237243
a[preference.identifier()] = db_pref.value
238244

245+
if cache_prefs:
246+
self.to_cache(*cache_prefs)
247+
239248
return a

0 commit comments

Comments
 (0)