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)
如您所见,在尝试添加任何内容之前,我正在打印 session 表中的内容,但它是空的!([])
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屋!