Using flask extensions in flask blueprints


Question

I want to create a blueprint; not an issue with the current blueprint I have. I can do this.

But, say I wanted to use a flask extension in my application (for my case I want to integrate flask-Cache)?

Everything I've done so far has errored:

  • cache = Cache(my_blueprint)

  • importing Cache and various parts of Cache in varying guises

so something like flask-cache is simple enough to wrap around my app:

from flask.ext.cache import Cache
cache = Cache(app)

but using this in a blueprint or using with a blueprint I don't quite understand how right now.

EDIT: the less obvious solution was to crib from the extension and build my own library to import into the blueprint, but it is more work and I'm not quite done yet. extensions / blueprints don't seem to be compatible from my level of understanding right now.

1
12
6/16/2012 1:17:39 PM

Accepted Answer

In order to avoid circular imports you will want to create your cache instance separate from your application instance (you may want to consider switching to the app factory module if you are building something more complex).

cache.py

from flask_cache import Cache

cache = Cache()

foo.py

from flask import Blueprint
from cache import cache

mod = Blueprint(...)

@mod.route("/")
@cache.cached(timeout=50)
def index():
    return datetime.now().strfmtime("%Y-%m-%d %H:%M:%S")

app.py

from flask import Flask
from yourapp.cache import cache
from yourapp.foo import mod

app = Flask("yourapp")

# ... snip ...

cache.init_app(app)

# ... snip ...

app.register_blueprint(mod)
42
3/1/2018 5:17:10 AM

The only thing the application needs access to is the app-instance to create a cache.

Let's assume your code: cache = Cache(app) is in foo.py. But you wanna use the cache in bar.py which uses a Blueprint to register the routes.

foo.py:

from flask.ext.cache import Cache
cache = Cache(app)

from bar import mod
app.register_blueprint(mod)

The only thing you have to do in bar.py is importing the cache from foo.py and use it:

bar.py:

from foo import chache

mod = Blueprint(...)


@mod.route('/')
@cache.cached(timeout=50)
def index():
    return str(datetime.now())

Flask Cache Docs and Examples

EDIT: The example above has a problem with circiular imports. The way to go here is separate the app from the cache:

pack/__init__.py:

app = Flask(__name__)

from pack.views.general import mod
app.register_blueprint(mod)

pack/cache.py:

from flask.ext.cache import Cache

from pack import app

cache = Cache(app)

pack/views/general.py:

from flask import Blueprint
from pack.chache import chache

mod = Blueprint(...)


@mod.route('/')
@cache.cached(timeout=50)
def index():
    return str(datetime.now())

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon