一尘不染

在Flask中为SQLAlchemy结果集jsonify

flask

我正在尝试对Flask / Python中的SQLAlchemy结果集进行json化。

Flask邮件列表建议使用以下方法http://librelist.com/browser//flask/2011/2/16/jsonify-sqlalchemy-pagination-collection-result/#04a0754b63387f87e59dda564bde426e:

return jsonify(json_list = qryresult)

但是我得到以下错误:

TypeError: <flaskext.sqlalchemy.BaseQuery object at 0x102c2df90> 
is not JSON serializable

我在这里俯瞰什么?

我发现了这个问题:如何将SqlAlchemy结果序列化为JSON?这似乎非常相似,但是我不知道Flask是否具有某些使魔术变得更容易的魔术,如邮件列表中所建议的那样。

编辑:为澄清起见,这就是我的模型的样子

class Rating(db.Model):

    __tablename__ = 'rating'

    id = db.Column(db.Integer, primary_key=True)
    fullurl = db.Column(db.String())
    url = db.Column(db.String())
    comments = db.Column(db.Text)
    overall = db.Column(db.Integer)
    shipping = db.Column(db.Integer)
    cost = db.Column(db.Integer)
    honesty = db.Column(db.Integer)
    communication = db.Column(db.Integer)
    name = db.Column(db.String())
    ipaddr = db.Column(db.String())
    date = db.Column(db.String())

    def __init__(self, fullurl, url, comments, overall, shipping, cost, honesty, communication, name, ipaddr, date):
        self.fullurl = fullurl
        self.url = url
        self.comments = comments
        self.overall = overall
        self.shipping = shipping
        self.cost = cost
        self.honesty = honesty
        self.communication = communication
        self.name = name
        self.ipaddr = ipaddr
        self.date = date

阅读 1333

收藏
2020-04-04

共1个答案

一尘不染

看来你实际上尚未执行查询。请尝试以下操作:

return jsonify(json_list = qryresult.all())

[编辑]:jsonify的问题是,通常无法自动对对象进行jsonify。甚至Python的日期时间也会失败;)

我过去所做的就是在serialize需要序列化的类中添加一个额外的属性(例如)。

def dump_datetime(value):
    """Deserialize datetime object into string form for JSON processing."""
    if value is None:
        return None
    return [value.strftime("%Y-%m-%d"), value.strftime("%H:%M:%S")]

class Foo(db.Model):
    # ... SQLAlchemy defs here..
    def __init__(self, ...):
       # self.foo = ...
       pass

    @property
    def serialize(self):
       """Return object data in easily serializable format"""
       return {
           'id'         : self.id,
           'modified_at': dump_datetime(self.modified_at),
           # This is an example how to deal with Many2Many relations
           'many2many'  : self.serialize_many2many
       }
    @property
    def serialize_many2many(self):
       """
       Return object's relations in easily serializable format.
       NB! Calls many2many's serialize property.
       """
       return [ item.serialize for item in self.many2many]

现在,对于视图,我可以做到:

return jsonify(json_list=[i.serialize for i in qryresult.all()])

希望这可以帮助

2020-04-04