flask 做為可插拔式的微框架,當然少不了對緩存的支持,flask-cache 配置使用都比較方便
1、安裝
推薦使用 pip install flask-cache
2、配置和使用
from flask import Flask
from flask.ext.cache import Cache
import datetime
app = Flask(__name__)
cache = Cache(app,config={'CACHE_TYPE': 'simple'})
@app.route('/')
def hello():
return "hello, world!"
@app.route('/t')
@cache.cached(timeout=60*30)
def cached_page():
time = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
return "hello, world, what's your name, thank you!!... localtime: " + time
if __name__ == '__main__':
app.run()
配置cache時 加入 cache = Cache(app,config={'CACHE_TYPE': 'simple'}) 就可以了,更多復雜的配置見 http://pythonhosted.org/Flask-Cache/ 需要緩存某個視圖和方法時,只需要在其前面加上 @cache 裝飾器語法糖 裝飾即可
注意: cache.cached() 方法裝飾沒有參數的函數, cache.memoize() 方法裝修有參數的函數
