Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using flask extensions in flask blueprints

Tags:

python

flask

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.

like image 919
blueblank Avatar asked Jun 13 '12 17:06

blueblank


People also ask

How do you use blueprints in Flask?

To use any Flask Blueprint, you have to import it and then register it in the application using register_blueprint() . When a Flask Blueprint is registered, the application is extended with its contents.

Does Flask support extension?

There are a large number of Flask extensions available. A Flask extension is a Python module, which adds specific type of support to the Flask application. Flask Extension Registry is a directory of extensions available. The required extension can be downloaded by pip utility.

Is Flask blueprint necessary?

You don't have to use blueprints. Just import current_app as app in your routes.py (or views.py, whatever) and you are free to go.

What is the point of Flask blueprint?

Flask uses a concept of blueprints for making application components and supporting common patterns within an application or across applications. Blueprints can greatly simplify how large applications work and provide a central means for Flask extensions to register operations on applications.


1 Answers

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)
like image 94
Sean Vieira Avatar answered Sep 30 '22 23:09

Sean Vieira