代码如下:
# -*- coding: utf-8 -*-
import string
import random
from flask import Flask
from flask.ext.cache import Cache
SECRET_KEY = '\xfb\x12\xdf\xa1@i\xd6>V\xc0\xbb\x8fp\x16#Z\x0b\x81\xeb\x16'
DEBUG = True
CACHE_TYPE = 'memcached'
CACHE_DEFAULT_TIMEOUT = 3600 # 默认缓存1个小时
CACHE_KEY_PREFIX = 'test_' # 所有key之前添加前缀
CACHE_MEMCACHED_SERVERS = ['127.0.0.1:11211']
app = Flask(__name__)
app.config.from_object(__name__)
cache = Cache(app)
strings = string.ascii_lowercase
#: This is an example of a memoized function
@cache.memoize(60)
def hello(a):
print 'not from cache {0}'.format(a)
return strings[a] + random.choice(strings)
def get_dict_by_ids(func, ids):
"""
:param func: 有cache.memoize装饰的方法
:params ids: id列表
"""
if not ids:
return
# cache_key列表
cache_key_list = []
for item_id in ids:
cache_key = func.make_cache_key(func.uncached, item_id)
cache_key_list.append(cache_key)
# 批量获取缓存
items = cache.get_many(*cache_key_list)
uncached_dict = {}
# 单独获取缓存中没有的数据, 应该使用set_many设置缓存
for (index, item) in enumerate(items):
if item is None:
item_id = ids[index]
cache_key = cache_key_list[index]
value = hello.uncached(item_id)
items[index] = value
uncached_dict[cache_key] = value
if uncached_dict:
cache.set_many(uncached_dict, timeout=func.cache_timeout)
return dict(zip(ids, items))
@app.route('/many')
def delete_cache():
cache.delete_memoized(hello)
print hello(1)
print hello(3)
print get_dict_by_ids(hello, [1, 2, 3])
return 'OK'
if __name__ == '__main__':
app.run(host='0.0.0.0')