Flask Cache
在開發flask 應用程式時,若是會往backend要很多次重複的資料,或是當service負載變重時,可以使用 flask cache 的方式,方便直接加上decorator 來採用 cache。
install Flask-Cache
pip install Flask-Cache
flask-cache for blueprint
cache.py
先準備一個 cache file
#coding=utf-8 from flask.ext.cache import Cache cache = Cache(config={'CACHE_TYPE':'simple'})
- 可選的 CACHE_TYPE 可以參考 docs
Built-in cache types: null: NullCache (default) simple: SimpleCache memcached: MemcachedCache (pylibmc or memcache required) gaememcached: GAEMemcachedCache redis: RedisCache (Werkzeug 0.7 required) filesystem: FileSystemCache saslmemcached: SASLMemcachedCache (pylibmc required)
views.py
在view 中使用 flask-cache
from cache import cache #cache 的時間 CACHE_G_TIME=500
一個使用範例
class ListView(MethodView): @cache.cached(CACHE_G_TIME,key_prefix=make_cache_key) def get(self,page=1,board='',author='',long_mode=0): #posts=Post.objects.all() page=request.args.get('page', 1) per_page=request.args.get('per_page', 10)
def make_cache_key(*args, **kwargs): #print 'request url : %s ' % request.url return request.url
這邊可以特別注意的是,除了 timeout的設定以外,還有是用一個key_prefix func。 預設在Flask-Cache 內的 cache key 是 request path ,要是你的url 有帶其他的 parameter 會被是成同一個key,所以加上了key_prefix的func來處理帶有parameter 的 url。
cached(timeout=None, key_prefix='view/%s', unless=None) Decorator. Use this to cache a function. By default the cache key is view/request.path. You are able to use this decorator with any function by changing the key_prefix. If the token %s is located within the key_prefix then it will replace that with request.path
使用了cache 以後在單位時間的同樣request都被cache起來,backend service著實減少不少負擔。
Ref:
- thadeusb/flask-cache https://github.com/thadeusb/flask-cache/
- Flask-Cache — Flask-Cache 0.13 documentation https://pythonhosted.org/Flask-Cache/
- Using Flask Cache | python | flask | BrunoRocha.org | Python web development http://brunorocha.org/python/flask/using-flask-cache.html
- python - Using flask extensions in flask blueprints - Stack Overflow http://stackoverflow.com/questions/11020170/using-flask-extensions-in-flask-blueprints
- python - What does
key_prefix
do for flask-cache? - Stack Overflow http://stackoverflow.com/questions/14228985/what-does-key-prefix-do-for-flask-cache