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

1

10

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.

Leonaleonanie answered 31/1, 2017 at 20:44 Comment(0)
S
8

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)
Spider answered 7/3, 2017 at 6:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.