3
Illustrate how to load some data, and cache the results.
7
from environment import Session
8
from model import Person
9
from caching_query import FromCache
11
# load Person objects. cache the result under the namespace "all_people".
12
print "loading people...."
13
people = Session.query(Person).options(FromCache("default")).all()
15
# remove the Session. next query starts from scratch.
18
# load again, using the same FromCache option. now they're cached
19
# under "all_people", no SQL is emitted.
20
print "loading people....again!"
21
people = Session.query(Person).options(FromCache("default")).all()
23
# want to load on some different kind of query ? change the namespace
24
# you send to FromCache
25
print "loading people two through twelve"
26
people_two_through_twelve = Session.query(Person).\
27
options(FromCache("default")).\
28
filter(Person.name.between("person 02", "person 12")).\
31
# the data is cached under the "namespace" you send to FromCache, *plus*
32
# the bind parameters of the query. So this query, having
33
# different literal parameters under "Person.name.between()" than the
34
# previous one, issues new SQL...
35
print "loading people five through fifteen"
36
people_five_through_fifteen = Session.query(Person).\
37
options(FromCache("default")).\
38
filter(Person.name.between("person 05", "person 15")).\
42
# ... but using the same params as are already cached, no SQL
43
print "loading people two through twelve...again!"
44
people_two_through_twelve = Session.query(Person).\
45
options(FromCache("default")).\
46
filter(Person.name.between("person 02", "person 12")).\
50
# invalidate the cache for the three queries we've done. Recreate
51
# each Query, which includes at the very least the same FromCache,
52
# same list of objects to be loaded, and the same parameters in the
53
# same order, then call invalidate().
54
print "invalidating everything"
55
Session.query(Person).options(FromCache("default")).invalidate()
56
Session.query(Person).\
57
options(FromCache("default")).\
58
filter(Person.name.between("person 02", "person 12")).invalidate()
59
Session.query(Person).\
60
options(FromCache("default", "people_on_range")).\
61
filter(Person.name.between("person 05", "person 15")).invalidate()