1

I am trying to add some roles/users with flask_security but run into this issue when I try to create users with the SQLAlchemySessionUserDatastore. So I first start by creating user_datastore like the guide

db = SQLAlchemy(app)
user_datastore = SQLAlchemySessionUserDatastore(db, User, Role)
security = Security(app, user_datastore)
user_datastore.create_user(email='test', password='passowrd')

this is where I deviate from the guide and try to just create a test user. Looks like the db = SQLAlchemy(app) is causing me issues.

    self.db.session.add(model)
AttributeError: 'SQLAlchemy' object has no attribute 'add'
michael
  • 113
  • 9

3 Answers3

6

user_datastore = SQLAlchemySessionUserDatastore(db, User, Role)

The above line may be the culprit here.

My resolution is below: user_datastore = SQLAlchemySessionUserDatastore(db.session, User, Role)

dione town
  • 61
  • 1
  • 3
3

From this line remove Session

user_datastore = SQLAlchemySessionUserDatastore(db, User, Role)

change to

user_datastore = SQLAlchemyUserDatastore(db, User, Role)

also imported

from flask_security import SQLAlchemyUserDatastore
GooDeeJAY
  • 1,681
  • 2
  • 20
  • 27
Shiraj Ali
  • 31
  • 1
2

So if you were following the example here https://pythonhosted.org/Flask-Security/quickstart.html#id2 you will notice they use SQLAlchemySessionUserDatastore. Before getting to this point if you have been starting off with just flask_sqlalchemy you would of probably already had a db session. So when I narrowed it down to the object SQLAlchemy not having add attribute I tried to use the sessionmaker. In which I was responded with db session already exists and now I have 2 sessions.

Long story short reading some docs you should use SQLAlchemyUserDatastore instead!

michael
  • 113
  • 9