出于安全原因,你永远不应回到所有模式领域。 我更喜欢有选择地选择。
Flask s json encoding is now support UUID,datetime and relations (and supplemented query
and query_}/code> for flask_sqlalchemy db.Model
. 一. 更新内容如下:
app/json_encoder.py
from sqlalchemy.ext.declarative import DeclarativeMeta
from flask import json
class AlchemyEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o.__class__, DeclarativeMeta):
data = {}
fields = o.__json__() if hasattr(o, __json__ ) else dir(o)
for field in [f for f in fields if not f.startswith( _ ) and f not in [ metadata , query , query_class ]]:
value = o.__getattribute__(field)
try:
json.dumps(value)
data[field] = value
except TypeError:
data[field] = None
return data
return json.JSONEncoder.default(self, o)
app/__init__py
# json encoding
from app.json_encoder import AlchemyEncoder
app.json_encoder = AlchemyEncoder
有了这一点,我可以选择性地添加一个<代码>__json__,归还我希望编码的田地清单:
app/models.py
class Queue(db.Model):
id = db.Column(db.Integer, primary_key=True)
song_id = db.Column(db.Integer, db.ForeignKey( song.id ), unique=True, nullable=False)
song = db.relationship( Song , lazy= joined )
type = db.Column(db.String(20), server_default=u audio/mpeg )
src = db.Column(db.String(255), nullable=False)
created_at = db.Column(db.DateTime, server_default=db.func.now())
updated_at = db.Column(db.DateTime, server_default=db.func.now(), onupdate=db.func.now())
def __init__(self, song):
self.song = song
self.src = song.full_path
def __json__(self):
return [ song , src , type , created_at ]
我认为,我加上@jsonapi,把结果清单退回,然后我的产出如下:
[
{
"created_at": "Thu, 23 Jul 2015 11:36:53 GMT",
"song":
{
"full_path": "/static/music/Audioslave/Audioslave [2002]/1 Cochise.mp3",
"id": 2,
"path_name": "Audioslave/Audioslave [2002]/1 Cochise.mp3"
},
"src": "/static/music/Audioslave/Audioslave [2002]/1 Cochise.mp3",
"type": "audio/mpeg"
}
]