Skip to content

Commit b5994ab

Browse files
committed
Baked Query Support
1 parent 31bc218 commit b5994ab

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

README.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,16 @@ being cached, try using a deferred query like:
4646
YourModel.query.options(defer('crazy_column')).options(FromCache(cache)).get()
4747
```
4848

49+
You can also integrate with [baked queries](https://docs.sqlalchemy.org/en/13/orm/extensions/baked.html) like so:
50+
```python
51+
baked_query = bakery(lambda session: session.query(YourModel))
52+
baked_query += lambda q: q.filter(YourModel.id == bindparam('id'))
53+
54+
obj = baked_query(YourModel.query.session) \
55+
.with_post_criteria(lambda q: q.options(FromCache(cache))) \
56+
.params(id=id).one()
57+
```
58+
4959
Take a look at [Dogpile Caching example][] to more details about how
5060
`CachingQuery` works. Most changes to their were made just to integrate it
5161
with Flask, Flask-SQLAlchemy and Flask-Caching instead of Dogpile.

flask_sqlalchemy_caching/core.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,6 +51,29 @@ def create_func(): return list(BaseQuery.__iter__(self))
5151
else:
5252
return BaseQuery.__iter__(self)
5353

54+
def _execute_and_instances(self, context):
55+
"""override _execute_and_instances to pull results from dogpile
56+
if the query is invoked directly from an external context.
57+
This method is necessary in order to maintain compatibility
58+
with the "baked query" system now used by default in some
59+
relationship loader scenarios. Note also the
60+
RelationshipCache._generate_cache_key method which enables
61+
the baked query to be used within lazy loads.
62+
.. versionadded:: 1.2.7
63+
"""
64+
super_ = super(CachingQuery, self)
65+
66+
if context.query is not self and hasattr(self, "_cache"):
67+
# special logic called when the Query._execute_and_instances()
68+
# method is called directly from the baked query
69+
return iter(
70+
self.get_value(
71+
createfunc=lambda: list(super_._execute_and_instances(context))
72+
)
73+
)
74+
else:
75+
return super_._execute_and_instances(context)
76+
5477
def _get_cache_plus_key(self):
5578
"""Return a cache region plus key."""
5679
return self._cache.cache, self._get_key()

0 commit comments

Comments
 (0)