我正在使用Flask和Flask-Login进行用户身份验证。 Flask-Sqlalchemy将这些模型存储在sqlite数据库中:
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
我的登录代码:
@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')
当我尝试登录时,SQLAlchemy会触发错误,您可以在帖子标题(TypeError: <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7f86789f9bf8> is not JSON serializable
)中看到错误。 AFAIK,InstumentedAttribute用于关系,但它对我没有帮助
我还发现在执行login_user()时发生错误。没有登录的注册工作正常
我怎么解决它?
答案 0 :(得分:0)
现在get_id()
在文档中同时返回一个整数:
get_id()
此方法必须返回唯一标识的unicode 此用户,可用于从user_loader加载用户 打回来。请注意,这必须是unicode - 如果ID本身是一个 int或其他类型,您需要将其转换为unicode 。
我写这个来解决问题:
def get_id(self):
return str(self.id)