title: SQLAlchemy Object already attached to session
body: <p>I'm trying to get a server for an app working, but I'm getting an error upon login:</p>
  
  <pre><code>[!] Object '&lt;User at 0x7f12bc185a90&gt;' is already attached to session '2' (this is '3')
  </code></pre>
  
  <p>It seems the session I'm adding is already on the database. This is the snippet of code that is causing the problem:</p>
  
  <pre><code>@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)
  </code></pre>
  
  <p>As you can see, I'm printing the content from the sessions table before trying to add anything, and it is empty! ([])</p>
  
  <p>What else could be causing this?</p>
  
  <p>Here is the 'Session' implementation:</p>
  
  <pre><code>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 '&lt;Session %r&gt;' % (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 &gt; 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 &gt; settings.SESSION_LIFETIME:
          s.query.delete()
          db_session.commit()
          s = None
      return s
  </code></pre>