I followed a tutorial of Flask-Cache and tried to implement it myself. Given the following example, why would Flask not cache the 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()
Output is always the current time.
It seems like the cache is recreated every single request. What am I doing wrong?
Edit: I execute 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()
You are using the SimpleCache
setup:
cache = Cache(config={'CACHE_TYPE': 'simple'})
This uses a single global dictionary to hold the cache, and this in turn will only work if you are using 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 handle requests, you'll get a new copy of that dictionary each time and nothing is cached, effectively.
The code works fine when run with the built-in app.run()
development server, given you don't use the processes
argument.
Your update shows that you run the server with 5 separate processes. Each process will get its own dictionary, and the cache is not shared between them. Use a different caching backend instead, like filesystem
:
cache = Cache(config={'CACHE_TYPE': 'filesystem', 'CACHE_DIR': '/tmp'})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With