我试图让一个应用程序的服务器工作,但登录时出错:

[!] Object '<User at 0x7f12bc185a90>' is already attached to session '2' (this is '3')

我要添加的会话似乎已在数据库中。这是导致问题的代码片段:
@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)

如您所见,我正在打印会话表中的内容,然后再尝试添加任何内容,它是空的!([)]
还有什么可能导致这种情况?
以下是“会话”实现:
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_会话是一个新实例。
一个很好的解决方法是提取当前绑定的会话并使用它:
而不是:

db_session.add(s)

做:
current_db_sessions = db_session.object_session(s)
current_db_sessions.add(s)

关于python - SQLAlchemy对象已附加到 session ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24291933/

10-10 07:29