def add_values():
# [START add_values]
# Add a value if it doesn't exist in the cache
# with a cache expiration of 1 hour.
memcache.add(key="weather_USA_98105", value="raining", time=3600)
# Set several values, overwriting any existing values for these keys.
memcache.set_multi(
{"USA_98115": "cloudy", "USA_94105": "foggy", "USA_94043": "sunny"},
key_prefix="weather_",
time=3600
)
# Atomically increment an integer value.
memcache.set(key="counter", value=0)
memcache.incr("counter")
memcache.incr("counter")
memcache.incr("counter")
# [END add_values]
python类set_multi()的实例源码
def cache_store(key, value, time=30, chunksize=950000):
serialized = pickle.dumps(value, 2)
values = {}
for i in xrange(0, len(serialized), chunksize):
values['%s.%s' % (key, i//chunksize)] = serialized[i : i+chunksize]
memcache.set_multi(values,time)
def get(self):
# [START batch]
values = {'comment': 'I did not ... ', 'comment_by': 'Bill Holiday'}
if not memcache.set_multi(values):
logging.error('Unable to set Memcache values')
tvalues = memcache.get_multi(('comment', 'comment_by'))
self.response.write(tvalues)
# [END batch]
def save_objects(self, keys_to_objects):
if not keys_to_objects:
return
memcache_set = {}
for k, v in keys_to_objects.iteritems():
if self._is_cacheable(k, v):
cache_key = self.key_to_cache_key(k)
memcache_set[cache_key] = v
memcache.set_multi(memcache_set, 2 * 3600)
def _save(self):
"""Internal function to save the recorded data to memcache.
Returns:
A tuple (key, summary_size, full_size).
"""
part, full = self.get_both_protos_encoded()
key = make_key(self.start_timestamp)
errors = memcache.set_multi({config.PART_SUFFIX: part,
config.FULL_SUFFIX: full},
time=36*3600, key_prefix=key,
namespace=config.KEY_NAMESPACE)
if errors:
logging.warn('Memcache set_multi() error: %s', errors)
return key, len(part), len(full)