Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.5k views
in Technique[技术] by (71.8m points)

Flask-Cache 报错:KeyError: 'cache'

下面的代码:

from flask import Flask
from flask_cache import Cache

app = Flask(__name__)

cache = Cache(config={'CACHE_TYPE': 'simple'})


@app.route('/test_cache')
@cache.cached(timeout=5)
def hello_world():
    print('if cache,the second request do not print')
    return 'Hello, World!'

运行:flask run,然后请求:curl http://127.0.0.1:5000/test_cache,有报错:

Exception possibly due to cache backend.
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask_cache/__init__.py", line 289, in decorated_function
    rv = self.cache.get(cache_key)
  File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/flask_cache/__init__.py", line 192, in cache
    return app.extensions['cache'][self]
KeyError: 'cache'

请问,是什么原因?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

上面这种写法,需要加上这段代码:cache.init_app(app)
详见代码仓库:https://github.com/cag2050/fl...


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...