pip3 install flask_cache
from flask import Flask
from flask_cache import Cache # pip3 install flask_cache
config = {
'CACHE_TYPE': 'redis',
'CACHE_REDIS_HOST': 'xx.xx.xx.xx', # redis ip
'CACHE_REDIS_PORT': 6379, # port
'CACHE_REDIS_DB': '2', # 使用的redis db
'CACHE_REDIS_PASSWORD': ''
}
app = Flask(__name__)
#cache = Cache(app=app,config=config) # moudle flask.ext not found
cache = Cache(app=app,config=config,with_jinja2_ext=False)
@app.route('/')
@cache.cached(timeout=50,key_prefix='view_%s') # key_prefix 指定redis以路由名为key
def index():
return 'hello'
if __name__ == "__main__":
print('server started')
app.run(host='0.0.0.0',port='8540')
cache = Cache(app=app,config=config,with_jinja2_ext=False)
#cache = Cache(app=app,config=config) # moudle flask.ext not found
Cache 如果不指定with_jinja2_ext=False 会出现No module named 'flask.ext’报错:
Traceback (most recent call last):
File "/data/workspace/test/flask_websocket/ws_server.py", line 17, in
cache = Cache(app=app,config=config) # moudle flask.ext not found
File "/usr/local/python3/lib/python3.6/site-packages/flask_cache/__init__.py", line 121, in __init__
self.init_app(app, config)
File "/usr/local/python3/lib/python3.6/site-packages/flask_cache/__init__.py", line 156, in init_app
from .jinja2ext import CacheExtension, JINJA_CACHE_ATTR_NAME
File "/usr/local/python3/lib/python3.6/site-packages/flask_cache/jinja2ext.py", line 33, in
from flask.ext.cache import make_template_fragment_key
ModuleNotFoundError: No module named 'flask.ext'
访问localhost:8540 后redis中写入了key 为flask_cache_view_/ 数据为 hello的缓存。