TypeError: sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7f86789f9bf8 is not JSON serializable

3.5k Views Asked by At

I'm using Flask with Flask-Login for user authentication. Flask-Sqlalchemy stores these models in sqlite database:

ROLE_USER = 0
ROLE_ADMIN = 1

class Anonymous(AnonymousUserMixin):
  def __init__(self):
    self.username = 'Guest'

lm.anonymous_user = Anonymous

class User(UserMixin, db.Model):
 __tablename__ = "users"
 id = db.Column(db.Integer, primary_key = True)
 username = db.Column(db.String(64), index = True, unique = True)
 password = db.Column(db.String(20), index = False, unique = True)
 email = db.Column(db.String(120), index = True, unique = True)
 registered_on = db.Column('registered_on' , db.DateTime)
 role = db.Column(db.SmallInteger, default = ROLE_USER)

 def __repr__(self):
  return '<User %r>' % (self.username)

 def get_id(self):
  return User.id


class PostVote(db.Model):
 __tablename__ = "postvotes"
 post_id = db.Column(db.Integer, db.ForeignKey('posts.id'), primary_key = True)
 user_id = db.Column(db.Integer, default = 0)
 type = db.Column(db.Boolean, default = True)

class Post(db.Model):
 __tablename__ = "posts"
 id = db.Column(db.Integer, primary_key = True)
 body = db.Column(db.String(320))
 points = db.Column(db.Integer, default = 0)
 votes = db.relationship(PostVote)
 timestamp = db.Column(db.DateTime)
 user_id = db.Column(db.Integer, db.ForeignKey('users.id'))

 def __repr__(self):
  return '<Post %r>' % self.body

And my login code:

@app.route('/login', methods = ['GET', 'POST'])
def init_login():
 form = LoginForm()
 if request.method == 'GET':
     return render_template('login/index.html', form = form, active = 'login')
 if form.validate():
     uname = form.username.data
     passw = form.password.data
     print('DBG: Loginning ' + uname) #for debug purposes
     registered_user = User.query.filter_by(username = uname).first()
     if registered_user is None:
         flash('User not found')
         return render_template('/login/index.html', form=form, 
         msgtype = 'alert-warning', active = 'login')
     if check_passw(passw, registered_user.password):
         login_user(registered_user)
         session['username'] = uname
         return redirect(url_for('init_login_success'))
     else:
         flash('Incorrect password')
         return render_template('/login/index.html', form=form, 
         msgtype = 'alert-danger', active = 'login')
 return render_template('login/index.html', form = form, active = 'login')

When I trying logging in, SQLAlchemy fires error, which you can see in post title (TypeError: <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7f86789f9bf8> is not JSON serializable). AFAIK, InstumentedAttribute is used for relationships but it didn't help me.
I also found that error occurs then login_user() executed. Registration without logging in works normally.
How I can fix it?

1

There are 1 best solutions below

2
On

Right now get_id() is returning an integer meanwhile in documentation:

get_id()
This method must return a unicode that uniquely identifies this user, and can be used to load the user from the user_loader callback. Note that this must be a unicode - if the ID is natively an int or some other type, you will need to convert it to unicode.

I wrote this to solve the problem:

def get_id(self):
        return str(self.id)