我在使用Flask Framework构建应用程序时遇到了一个小问题。
我正在尝试创建一个简单的用户+权限模块。要对其进行存档,我在“用户和权限”表之间具有多对多关系。
这是我的模型,形式和路线
模型
user_perm = db.Table('user_perm',
db.Column('user_id', db.Integer, db.ForeignKey('user.id')),
db.Column('perm_id', db.Integer, db.ForeignKey('permissions.id'))
)
class User(db.Model):
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(32), unique=True, nullable=False)
pwdhash = db.Column(db.String(16), nullable=False)
email = db.Column(db.String(128))
permissions = db.relationship('Permission', secondary=user_perm, backref=db.backref('users', lazy='dynamic'))
def __init__(self, username, pwdhash, email, perms):
self.username = unicode(username)
self.pwdhash = pwdhash
self.email = email
self.permissions = perms
def __repr__(self):
return '<User {0}>'.format(self.username)
class Permission(db.Model):
__tablename__ = 'permissions'
id = db.Column(db.Integer)
perm = db.Column(db.String(50), primary_key=True, unique=True, nullable=False)
def __init__(self, perm):
self.perm = unicode(perm)
def __repr__(self):
return '<Permission {0}>'.format(self.perm)
表格
class AddUser(Form):
username = TextField(u'Username', required)
pwdhash = TextField(u'Password', required)
email = TextField(u'E-email', email_validators)
permissions = SelectMultipleField(u'Permissions', required, coerce=int)
class EditUser(AddUser):
pass
路线
@app.route('/admin/user/add', methods=['GET', 'POST'])
@login_required
def admin_user_add():
form = AddUser(request.form)
form.permissions.choices = [(p.id, p.perm) for p in Permission.query.order_by('perm')]
if request.method == 'POST' and form.validate():
user = User(
form.username.data,
form.pwdhash.data,
form.email.data,
Permission.query.filter(Permission.id.in_(form.permissions.data)).all()
)
db.session.add(user)
db.session.commit()
flash('Successfully added user', category='success')
return redirect(url_for('users'))
return render_template('admin_user_add.html', form=form)
@app.route('/admin/user/edit/<int:user_id>', methods=['GET', 'POST'])
@login_required
def admin_user_edit(user_id):
user = User.query.filter_by(id=user_id).first_or_404()
form = EditUser(request.form, obj=user)
form.permissions.choices = [(p.id, p.perm) for p in Permission.query.order_by('perm')]
form.permissions.data = [p.id for p in user.permissions]
if request.method == 'POST' and form.validate():
form.populate_obj(user)
user.username = form.username.data
user.pwdhash = form.pwdhash.data
user.email = form.email.data
user.permissions = Permission.query.filter(Permission.id.in_(form.permissions.data)).all()
db.session.merge(user)
db.session.commit()
flash('Successfully updated user', category='success')
return redirect(url_for('users'))
return render_template('admin_user_add.html', form=form, edit=True)
添加操作可以正常工作,关系已添加,但是当我尝试编辑用户时,出现此错误。
追溯
Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1518, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1506, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1504, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1264, in full_dispatch_request
rv = self.handle_user_exception(e)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1262, in full_dispatch_request
rv = self.dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1248, in dispatch_request
return self.view_functions[rule.endpoint](**req.view_args)
File "/var/www/deploy.staging.inovae.ch/webapp/webapp/utilities.py", line 29, in inner
return f(*args, **kwargs)
File "/var/www/deploy.staging.inovae.ch/webapp/webapp/utilities.py", line 44, in wrapper
return f(*args, **kwargs)
File "/var/www/deploy.staging.inovae.ch/webapp/webapp/views.py", line 161, in admin_user_edit
form.populate_obj(user)
File "/usr/local/lib/python2.7/dist-packages/wtforms/form.py", line 73, in populate_obj
field.populate_obj(obj, name)
File "/usr/local/lib/python2.7/dist-packages/wtforms/fields/core.py", line 283, in populate_obj
setattr(obj, name, self.data)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 155, in __set__
instance_dict(instance), value, None)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 892, in set
lambda adapter, i: adapter.adapt_like_to_iterable(i))
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 927, in _set_iterable
collections.bulk_replace(new_values, old_collection, new_collection)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/collections.py", line 681, in bulk_replace
new_adapter.append_with_event(member)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/collections.py", line 555, in append_with_event
getattr(self._data(), '_sa_appender')(item, _sa_initiator=initiator)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/collections.py", line 945, in append
item = __set(self, item, _sa_initiator)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/collections.py", line 920, in __set
item = getattr(executor, 'fire_append_event')(item, _sa_initiator)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/collections.py", line 614, in fire_append_event
item, initiator)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/attributes.py", line 800, in fire_append_event
value = fn(state, value, initiator or self)
File "/usr/local/lib/python2.7/dist-packages/sqlalchemy/orm/unitofwork.py", line 35, in append
item_state = attributes.instance_state(item)
AttributeError: 'long' object has no attribute '_sa_instance_state'
最佳答案
问题的原因
问题的症结在于 SQL Alchemy期望permissions
关系使用sqlalchemy permission
对象填充,而不是您要传递的int
填充。
您认为:
form = EditUser(request.form, obj=user)
form.permissions.choices = [(p.id, p.perm) for p in Permission.query.order_by('perm')]
form.permissions.data = [p.id for p in user.permissions]
因此,在您的表单中,
form.permissions
实际上只是保存权限对象的id
(int),而不是对象本身。当您调用form.populate_obj(user)
时,当它进入权限段时,它将调用此方法:setattr(obj, name, self.data)
转换为:
setattr(user, permissions, sefl.data)
转换为:
user.permissions = [1, 3, 4 ...]
但是SQL Alchemy期望:
user.permissions = [sqlalchemyobject1, sqlalchemyobject2, ...]
解决方案
至少有几种方法可以解决此问题。我使用的方法是sqlalchemy的Association Proxy。这将使您能够执行一些操作,例如将整数列表传递给用户模型,然后让模型将其转换为Permissions对象:
class User(db.Model):
...
permissions_relationship = ('Permission', cascade="all,delete,delete-orphan")
permissions = association_proxy('permissions_relationship', 'perm',
creator=lambda perm: Permission(perm=perm)
class Permission(db.Model):
...
perm = ...
def __init__(self,perm):
self.perm = perm
简而言之,
association_proxy
调用简单地说:“当您传递项目列表(整数,字符串等)时,请执行以下操作将它们转换为Permission
对象:Permission(perm=perm)
。在上面的代码中使用此解决方案,您将删除行form.permissions.data = [p.id for p in user.permissions]
。最后,
wtforms
还提供了QuerySelectMultiple field。我没有使用过它,但是可以想象它也可以解决这个问题。关于python - 如何使用WTForms和SQLAlchemy进行多对多数据更新?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9885693/