遇到的问题:

通过sqlalchemy查询的结果,如果直接通过jsonify函数转为json会报错:

TypeError: Object of type 'Comment' is not JSON serializable
网上有各种方案,例如增加一个AlchemyEncoder类来专门处理,但是本人试过都不行,以下方案才是正解:

1. 需要在模型类中增加to_json函数:

class Comment(db.Model): __tablename__ = 't_comment' id = db.Column(db.Integer, primary_key=True, autoincrement=True) content = db.Column(db.Text, nullable=False) create_time = db.Column(db.DateTime, nullable=False, default=datetime.now) author_id = db.Column(db.Integer, db.ForeignKey('t_user.id')) question_id = db.Column(db.Integer, db.ForeignKey('t_question.id')) author = db.relationship('User', backref=db.backref('comments')) question = db.relationship('Question', backref=db.backref('comments', order_by=create_time.desc()))   def to_json(self):   dict = self.__dict__   if "_sa_instance_state" in dict:   del dict["_sa_instance_state"]   return dict

2. 将查询的结果,一次通过to_json方法放到数组中,在通过jsonify函数返回到前台:

# rest api接口,并将查询结果转化为json @app.route('/comments', methods=['GET']) def comments():   comments = db.session.query(Comment).all()   result = []   for comment in comments:     result.append(comment.to_json())   return jsonify(result), 200