3

I using Flask-Security with SQLAlchemy

When want to add user or role

def addrole():
        form=addroll()
        createRole=user_datastore.create_role(name=form.role.data,description=form.description.data)
        db.session.add(createRole)
        db.session.commit()

in mysql table add one record belong my creation and two or tree blank record same think happen when i want to create user To associate a user with a role, I have the following :

   @app.route('/addR', methods=['GET', 'POST'])
   @login_required
   def addR():
      email1=request.form['emails']
      role1=request.form['role2']
      user = user_datastore.find_user(email=request.args.get('email1'))
      role = user_datastore.find_role(request.args.get('role1'))
      user_datastore.add_role_to_user(user, role)
      db.session.commit()
      return  redirect('/addroletouser' )

It linking a wrong user_id and role_id in roles_users table.

garni
  • 45
  • 1
  • 8

1 Answers1

4

When using Flask-Security with SQLAlchemy you do not need to manually link the records, you can use create_role and create_user from the user_datastore. This is the same user_datastore that you used to initialise Flask-Security. A simple example (do not use plain text password please):

def seed():
  user_datastore.create_role(name='admin')
  user_datastore.create_user(username='admin', email='admin@example.com',
                             password='admin', roles=['admin'])
rll
  • 5,509
  • 3
  • 31
  • 46
  • When I seed the data, I added the code like above. but since we don't add any custom code for registration, how does create_role gets triggered? how do I make it add role on registration ? – JPro Aug 27 '16 at 13:56
  • I don't understand your question. The helpers come with the Flask-Security extension. This is a seed method, you call it on startup. You should create your roles when seeding. Then add a default role for regular users when you create them, and you'll need somewhat custom forms (depends on your app architecture). I use it conjunction with Flask-Admin and WTForms and it may be a good starting point for you. – rll Sep 14 '16 at 12:35
  • @JPro Use a .click command to be able to insert some admin users on production database. – Jonathan Scholbach Sep 18 '17 at 07:49