Skip to content

Commit c905755

Browse files
elibixbyJon Wayne Parrott
authored and
Jon Wayne Parrott
committed
Add memcache snippets
1 parent 7b9ee96 commit c905755

File tree

2 files changed

+74
-0
lines changed

2 files changed

+74
-0
lines changed

appengine/memcache/snippets.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# [START import]
2+
from google.appengine.api import memcache
3+
# [END import]
4+
5+
6+
def query_for_data():
7+
return 'data'
8+
9+
10+
# [START get_data]
11+
def get_data():
12+
data = memcache.get('key')
13+
if data is not None:
14+
return data
15+
else:
16+
data = query_for_data()
17+
memcache.add('key', data, 60)
18+
return data
19+
# [END get_data]
20+
21+
22+
def add_values():
23+
# [START add_values]
24+
# Add a value if it doesn't exist in the cache
25+
# with a cache expiration of 1 hour.
26+
memcache.add(key="weather_USA_98105", value="raining", time=3600)
27+
28+
# Set several values, overwriting any existing values for these keys.
29+
memcache.set_multi(
30+
{"USA_98115": "cloudy", "USA_94105": "foggy", "USA_94043": "sunny"},
31+
key_prefix="weather_",
32+
time=3600
33+
)
34+
35+
# Atomically increment an integer value.
36+
memcache.set(key="counter", value=0)
37+
memcache.incr("counter")
38+
memcache.incr("counter")
39+
memcache.incr("counter")
40+
# [END add_values]

appengine/memcache/snippets_test.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
from google.appengine.api import memcache
2+
from mock import patch
3+
import snippets
4+
5+
SNIPPET_VALUES = {
6+
"weather_USA_98105": "raining",
7+
"weather_USA_98115": "cloudy",
8+
"weather_USA_94105": "foggy",
9+
"weather_USA_94043": "sunny",
10+
"counter": 3,
11+
}
12+
13+
14+
@patch('snippets.query_for_data', return_value='data')
15+
def test_get_data_not_present(query_fn, testbed):
16+
data = snippets.get_data()
17+
query_fn.assert_called_once_with()
18+
assert data == 'data'
19+
memcache.delete('key')
20+
21+
22+
@patch('snippets.query_for_data', return_value='data')
23+
def test_get_data_present(query_fn, testbed):
24+
memcache.add('key', 'data', 9000)
25+
data = snippets.get_data()
26+
query_fn.assert_not_called()
27+
assert data == 'data'
28+
memcache.delete('key')
29+
30+
31+
def test_add_values(testbed):
32+
snippets.add_values()
33+
for key, value in SNIPPET_VALUES.iteritems():
34+
assert memcache.get(key) == value

0 commit comments

Comments
 (0)