BAE 上使用Cache 没有免费配额,但redis 是免费的,免费配额是10000条key-value数据,目前每条redis命令的有效长度最大为2048个字节,这使太长的数据不能放在redis 里面。
下面分享一个页面缓存函数:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
def pagecache(key="", time=300, key_suffix_calc_func=None):
def _decorate(method):
def _wrapper(*args, **kwargs):
req = args[0]
key_with_suffix = key
if key_suffix_calc_func:
key_suffix = key_suffix_calc_func(*args, **kwargs)
if key_suffix:
key_with_suffix = '%s:%s' % (key, key_suffix)
if key_with_suffix:
key_with_suffix = str(key_with_suffix)
else:
key_with_suffix = req.request.path
mc = BaeMemcache()
html = mc.get(key_with_suffix)
if html:
req.write(html)
else:
result = method(*args, **kwargs)
mc.set(key_with_suffix, result, time)
return _wrapper
return _decorate
函数使用方法:
1
2
3
4
5
6
7
8
9
10
11
12
class HomePage(BaseHandler):
@pagecache('post_index_page', 36000, lambda self: self.get_argument("page", 1))
def get(self):
page = int(self.get_argument("page", 1))
"""
.... your codes here ...
"""
# used tornado.web
output = self.render(.....)
self.write(output)
#important
return output