登录
首页 >  文章 >  python教程

Flask-SQLAlchemyORM对象序列化技巧,轻松避开序列化错误

时间:2025-03-17 15:03:07 105浏览 收藏

Flask-SQLAlchemy中直接将ORM对象序列化为JSON常导致“Object of type User is not JSON serializable”错误。本文提供了解决方案:为数据库模型类添加`to_dict()`方法,将ORM对象转换为字典格式。通过在Flask路由函数中使用`to_dict()`方法,并将结果用`jsonify()`函数返回,即可避免该错误,确保将数据正确传递给前端。文章以代码示例详细讲解了如何实现这一方法,有效解决Flask与SQLAlchemy结合使用中的常见序列化问题。

Flask-SQLAlchemy ORM对象如何序列化才能避免“Object of type User is not JSON serializable”错误?

Flask-SQLAlchemy ORM 对象序列化:避免“Object of type User is not JSON serializable”错误

在 Flask 和 SQLAlchemy 的结合使用中,直接将 ORM 对象序列化为 JSON 经常会导致 Object of type User is not JSON serializable 错误。本文将详细讲解如何解决此问题。

问题:

使用 Flask-SQLAlchemy 定义的数据库模型 (例如 User 模型),通过 User.query.all() 获取数据后,直接使用 jsonify() 函数返回给前端会引发上述错误。这是因为 jsonify() 无法直接序列化 SQLAlchemy 的 ORM 对象。

解决方案:

为了解决这个问题,需要将 ORM 对象转换为 JSON 可序列化的格式,例如字典。 我们可以为模型类添加一个 to_dict() 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from sqlalchemy import Column, Integer, String
from flask_sqlalchemy import SQLAlchemy
 
db = SQLAlchemy() # Assuming you've initialized your SQLAlchemy instance
 
class User(db.Model):
    __tablename__ = 'users'  # Replace 'users' with your table name
    id = Column(Integer, primary_key=True)
    app_key = Column(String(50), unique=True)
    secret = Column(String(120), unique=True)
 
    def __init__(self, app_key=None, secret=None):
        self.app_key = app_key
        self.secret = secret
 
    def to_dict(self):
        return {
            "id": self.id,
            "app_key": self.app_key,
            "secret": self.secret,
        }

然后,在 Flask 路由函数中使用 to_dict() 方法将对象转换为字典列表,再使用 jsonify() 返回:

1
2
3
4
5
6
7
8
9
10
11
12
from flask import Flask, jsonify
 
app = Flask(__name__)
# ... (your database configuration) ...
 
@app.route("/users")
def get_users():
    users = User.query.all()
    return jsonify([user.to_dict() for user in users])
 
if __name__ == '__main__':
    app.run(debug=True)

通过 to_dict() 方法,将 User 对象转换为 JSON 可序列化的字典,从而避免了序列化错误,确保正确的数据返回给前端。 这种方法是处理 SQLAlchemy ORM 对象序列化的常用且有效的方式。

好了,本文到此结束,带大家了解了《Flask-SQLAlchemyORM对象序列化技巧,轻松避开序列化错误》,希望本文对你有所帮助!关注golang学习网公众号,给大家分享更多文章知识!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>