在做分页接口时出现了Object of type Pagination is not JSON serializable,因为JSON的JSONEncoder不认识Pagination对象。对象不能序列化的问题,在这篇文章中有讲过:TypeError: Object of type XXX is not JSON serializable
为了让接口输出的json结果更美观,把页面的信息放在同一个key下,在序列化之前先进行一次处理。用的是装饰器来实现:
from functools import wraps
def package_paginate(func):
"""序列化化SQLAlchemy的paginate的输出"""
@wraps(func)
def decorator(cls, page, limit, *args):
paginate = func(cls, page, limit, *args)
results = {
"items": paginate.items,
"pageInfo": {
"counts": paginate.total,
"pages": paginate.pages,
"page": paginate.page,
"limit": paginate.per_page
}
}
return results
return decorator
?paginate的items就是Pagination里的Model对象的集合,这些item直接用JSONEncoder序列化即可
import datetime
import decimal
from flask.json import JSONEncoder as BaseJSONEncoder
from stock_flask.models.base_model import BaseModel
class JSONEncoder(BaseJSONEncoder):
def default(self, o):
if isinstance(o, datetime.datetime):
return o.strftime('%Y-%m-%d %H:%M:%S')
if isinstance(o, datetime.date):
return o.strftime('%Y-%m-%d')
if isinstance(o, datetime.time):
return o.strftime('%H:%M:%S')
if isinstance(o, decimal.Decimal):
return float(o)
if isinstance(o, BaseModel):
return o.to_json(o)
return super(JSONEncoder, self).default(o)
BaseModel继承自Model,并实现了to_json()方法
from stock_flask.extensions import db
class BaseModel(db.Model):
@staticmethod
def to_json(obj):
res = {}
for c in obj.__table__.columns:
value = getattr(obj, c.name, '')
res[c.name] = value
return res
在实现paginate的方法上使用装饰器,并在视图函数输出结果时使用指定的JSONEncoder,即可使接口输出想要的json
?输出的效果:
?
|