Flask-Caching With Blueprints

Published: Thu 29 August 2019
Updated: Thu 29 August 2019

In Python.

Caching is really useful but can be a bit of a pain to set up when you’re also using blueprints in your Flask App.

The apparently obvious solution:

myapp/__init__.py

from flask import Flask
from flask_caching import Cache
from app_bp.controllers import bp

app = Flask()
cache = Cache(app)

app.register_blueprint(bp)

myapp/app_bp/controllers.py

from flask import Blueprint
from myapp import cache

bp = Blueprint('bp', __name__, template_folder='templates')

@bp.route('/')
@cache.cached()
def index():
    ...

results in some horrible circular imports. The solution here is to split the cache out into its own file and set up the cache using the init_app method mentioned in the docs: https://flask-caching.readthedocs.io/en/latest/#set-up. This results in the following structure:

myapp/cache.py

from flask_caching import Cache

cache = Cache(config={ "CACHE_TYPE": "simple",
                       "CACHE_DEFAULT_TIMEOUT": 300 } )

myapp/__init__.py

from flask import Flask
from haptic_feedback.cache import cache

app = Flask()
cache.init_app(app)

app.register_blueprint(bp)

myapp/app_bp/controllers.py

from flask import Blueprint
from myapp.cache import cache

bp = Blueprint('bp', __name__, template_folder='templates')

@bp.route('/')
@cache.cached()
def index():
    ...

With thanks to: https://stackoverflow.com/a/11027030/11034825 who saved me a lot of frustration getting to this point.

Pssst

There’s a really helpful tutorial about Using Flask Cache here: http://brunorocha.org/python/flask/using-flask-cache.html which includes details about caching blueprints and arbitrary objects (the thing I was mostly intending on doing for my application).

Comments


There are no comments yet.

Add a Comment

You can use Markdown to format your comment.

Buy me a coffee Buy me a coffee