Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flask-security: how to use in blueprint/extension app pattern?

I want to use flask-security. I'm using a template flask app which creates global objects for extensions, and then initialises them when the app is created. e.g. in extensions.py there is code like this:

from flask_bcrypt import Bcrypt
from flask_caching import Cache ...
from flask_security import Security ...
bcrypt = Bcrypt() ...
security = Security()

and then in app.py a call to register_extensions(app) which uses init_app(app) methods like so:

bcrypt.init_app(app)
security.init_app(app)

and indeed flask-security has an init_app() method. But the documentation says that the Security object needs a DataStore object which needs the User and Role model. It doesn't feel right to import the User and Role model in app.py when so far no other extension needs that.

What is the best practice for using Flask-Security when using the 'large Flask app' model ... I don't find the documentation helpful. It is a simple case when all objects are defined in one place.

like image 572
Tim Richardson Avatar asked Jan 31 '17 20:01

Tim Richardson


1 Answers

Below is what I have.

extensions.py

from flask_sqlalchemy import SQLAlchemy
from flask_security import Security


db = SQLAlchemy()
security = Security()

__init__.py

from .extensions import db, security
from .models import User, Role

def create_app(config_name):
    user_datastore = SQLAlchemyUserDatastore(db, User, Role)
    security.init_app(app, user_datastore)
like image 108
Stijn Diependaele Avatar answered Sep 21 '22 19:09

Stijn Diependaele