Skip to content

Commit 6f60025

Browse files
committed
✨ Make get and first cache keys match
Previously, the cache key generated for get() and first() were different because the names of the dictionary key containing the parms to bind where different ('id' if get, 'param' if first). This change injects the bound params into the query and then hashes that. The purpose for this change, was that previously, it was impossible to invalidate cache for a get() or get_or_404().
1 parent 0baab33 commit 6f60025

File tree

1 file changed

+5
-11
lines changed

1 file changed

+5
-11
lines changed

flask_sqlalchemy_caching/core.py

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,8 @@ def __iter__(self):
4444
the items in the cache are not the same ones in the current Session.
4545
"""
4646
if hasattr(self, '_cache'):
47-
func = lambda: list(BaseQuery.__iter__(self))
48-
return iter(self.get_value(createfunc=func))
47+
def create_func(): return list(BaseQuery.__iter__(self))
48+
return iter(self.get_value(createfunc=create_func))
4949
else:
5050
return BaseQuery.__iter__(self)
5151

@@ -98,21 +98,15 @@ def key_from_query(self, qualifier=None):
9898
Given a Query, create a cache key.
9999
100100
There are many approaches to this; here we use the simplest, which is
101-
to create an md5 hash of the text of the SQL statement, combined with
102-
stringified versions of all the bound parameters within it.
101+
to create an md5 hash of the text of the SQL statement compiled with
102+
the bound parameters in it.
103103
104104
There's a bit of a performance hit with compiling out "query.statement"
105105
here; other approaches include setting up an explicit cache key with a
106106
particular Query, then combining that with the bound parameter values.
107107
"""
108108
stmt = self.with_labels().statement
109-
compiled = stmt.compile()
110-
params = compiled.params
111-
112-
values = [str(compiled)]
113-
for k in sorted(params):
114-
values.append(repr(params[k]))
115-
key = u" ".join(values)
109+
key = str(stmt.compile(compile_kwargs={'literal_binds': True}))
116110
return md5(key.encode('utf8')).hexdigest()
117111

118112

0 commit comments

Comments
 (0)