I am building a web form using Flask and would like the user to be able to enter multiple entries, and give them the opportunity to regret an entry with an undo button, before sending the data to the database. I am trying to use Flask-Caching but have not managed to set it up properly.
I have followed The Flask Mega-Tutorial for setting up Flask (this is my first Flask app).
+---app
| | forms.py
| | routes.py
| | __init__.py
| +---static
| +---templates
I wonder how I need to configure the Flask app to basically be able to do the following things:
cache.add("variable_name", variable_data)
variable_name = cache.get("variable_name")
cache.clear()
in one of the pages (functions with @app.route decorators)?
In app.init.py I have:
from flask import Flask
from config import Config
from flask_caching import Cache
app = Flask(__name__)
app.config.from_object(Config)
cache = Cache(app, config={'CACHE_TYPE': 'simple'})
from app import routes
In routes.py I have:
from flask import current_app
and I use code below when I try to call the cache.
current_app.cache.add("variable_name", variable_data)
What I get when trying to use the form is the following error:
AttributeError: 'Flask' object has no attribute 'cache'
Pretty much all tutorials I've found have simply had the app declaration and all the routes in the same module. But how do I access the cache when I have the routes in another module?
You first statement makes me wonder if you are really looking for caching
. It seems you are looking for session data storage.
Some possibilities...
session
objects. From docs: This can be any small, basic information about that client or their interactions for quick retrieval (up to 4kB).Example session storing explicitly variable: username
from flask import Flask, session, request
app = Flask(__name__)
app.config["SECRET_KEY"] = "any random string"
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
session["username"] = request.form["username"]
# to get value use session["username"]
Must be stated that:
A cache's primary purpose is to increase data retrieval performance by reducing the need to access the underlying slower storage layer
So if you need to spee-up things on your site... this is the recommended approach by the Flask team.
Example of caching a variable username
that will expire after CACHE_DEFAULT_TIMEOUT
from flask import Flask, request
from flask_caching import Cache
app = Flask(__name__)
app.config["SECRET_KEY"] = "any random string"
app.config["CACHE_TYPE"] = "SimpleCache"
app.config["CACHE_DEFAULT_TIMEOUT"] = 300 # timeout in seconds
cache = Cache(app)
@app.route("/login", methods=["GET", "POST"])
def login():
if request.method == "POST":
cache.set("username", request.form["username"])
# to get value use cache.get("username")