Cache is not cached

I completed the tutorial in Flask-Cache and tried to implement it myself. Given the following example, why doesn't Flask cache time?

from flask import Flask import time app = Flask(__name__) cache = Cache(config={'CACHE_TYPE': 'simple'}) cache.init_app(app) @app.route('/time') @cache.cached(timeout=50, key_prefix='test') def test(): return time.ctime() 

The output is always current.

It seems that the cache is recreated every single request. What am I doing wrong?

Edit: I am executing the following python file with Python 2.7.6:

 def runserver(): port = int(os.environ.get('PORT', 5000)) Triangle(app) app.run(host='0.0.0.0', port=port, processes=5) if __name__ == '__main__': runserver() 
+7
python flask caching
source share
1 answer

You use the SimpleCache setting:

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

One global dictionary is used to store the cache, and this, in turn, will work only if you use a WSGI server that uses one Python interpreter to serve all your WSGI requests. If you use a WSGI server that uses separate child processes to process requests, you will get a new copy of this dictionary every time and nothing is cached efficiently.

The code works fine when run with the built-in development server app.run() , unless you use the processes argument.

Your update shows that you are starting a server with 5 separate processes. Each process will receive its own dictionary, and the cache is not used between them. Instead, use another caching server, for example filesystem :

 cache = Cache(config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp'}) 
+14
source share

All Articles