Flask-security create role,user and linking user_id to role_id

这一生的挚爱 提交于 2020-01-04 02:54:59

问题


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.


回答1:


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'])


来源:https://stackoverflow.com/questions/22410071/flask-security-create-role-user-and-linking-user-id-to-role-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!