Search code examples
pythonflaskcachingflask-caching

How to cache a variable with Flask?


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?


Solution

  • You first statement makes me wonder if you are really looking for caching. It seems you are looking for session data storage. Some possibilities...

    1. Session Data Storage

    • Client-Side: Store session client data as cookies using built-in Flask 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"]
    
    • Server-Side: For configurations or long-standing session data that usually still don't require a database. A more comprehensive example usage look here for the Flask-Session package.

    2. Caching (Flask-Caching package)

    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")