SQLAlchemy对象已附加到会话 [英] SQLAlchemy Object already attached to session
问题描述
我正在尝试为应用程序运行服务器,但登录时出现错误:
I'm trying to get a server for an app working, but I'm getting an error upon login:
[!] Object '<User at 0x7f12bc185a90>' is already attached to session '2' (this is '3')
似乎我要添加的会话已经在数据库中.这是引起问题的代码片段:
It seems the session I'm adding is already on the database. This is the snippet of code that is causing the problem:
@app.route('/login', methods=['POST'])
def login():
u = User.query.filter(User.username == request.form["username"]).first()
if not u or u.password != request.form["password"]:
return error("E1")
s = Session.get_by_user(u)
if s is not None:
db_session.delete(s)
db_session.commit()
print db_session.execute("SELECT * FROM sessions").fetchall()
s = Session(u)
db_session.add(s)
db_session.commit()
return jsonify(s.values)
如您所见,在尝试添加任何内容之前,我正在打印会话表中的内容,该内容为空! ([])
As you can see, I'm printing the content from the sessions table before trying to add anything, and it is empty! ([])
还有什么可能导致这种情况?
What else could be causing this?
这是会话"实现:
class Session(Base):
__tablename__ = "sessions"
id = Column(Integer, primary_key=True)
user_id = Column(Integer, ForeignKey('users.id'), unique=True)
user = relationship(User)
key = Column(String(50), unique=True)
created = Column(DateTime)
def __init__(self, user=None):
self.user = user
self.key = base64.encodestring(os.urandom(24)).strip()
self.created = datetime.now()
def __repr__(self):
return '<Session %r>' % (self.key)
@property
def values(self):
return {"username" : self.user.username,
"key" : self.key,
"created" : str(self.created),
}
@classmethod
def get_by_key(cls, key):
s = cls.query.filter(cls.key == key).first()
#print datetime.now() - s.created
if s and datetime.now() - s.created > settings.SESSION_LIFETIME:
s = None
return s
@classmethod
def get_by_user(cls, user):
s = cls.query.filter(cls.user == user).first()
if s and datetime.now() - s.created > settings.SESSION_LIFETIME:
s.query.delete()
db_session.commit()
s = None
return s
推荐答案
您要修改的对象已附加到另一个会话. 也许您导入错误,并且db_session是一个新实例.
Object you're trying to modify is already attached to another session. Maybe you have wrong imports, and db_session is a new instance.
一个好的解决方法是提取当前绑定的会话并使用它:
A good workaround to this is to extract the current bound session and use it:
代替:
db_session.add(s)
做:
current_db_sessions = db_session.object_session(s)
current_db_sessions.add(s)
这篇关于SQLAlchemy对象已附加到会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!