问题
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