当前位置:   article > 正文

flask踩坑记录:sqlalchemy使用paginate出现Object of type Pagination is not JSON serializable_flask object of type pagination is not json serial

flask object of type pagination is not json serializable

在做分页接口时出现了Object of type Pagination is not JSON serializable,因为JSON的JSONEncoder不认识Pagination对象。对象不能序列化的问题,在这篇文章中有讲过:TypeError: Object of type XXX is not JSON serializable

为了让接口输出的json结果更美观,把页面的信息放在同一个key下,在序列化之前先进行一次处理。用的是装饰器来实现:

  1. from functools import wraps
  2. def package_paginate(func):
  3. """序列化化SQLAlchemy的paginate的输出"""
  4. @wraps(func)
  5. def decorator(cls, page, limit, *args):
  6. paginate = func(cls, page, limit, *args)
  7. results = {
  8. "items": paginate.items,
  9. "pageInfo": {
  10. "counts": paginate.total,
  11. "pages": paginate.pages,
  12. "page": paginate.page,
  13. "limit": paginate.per_page
  14. }
  15. }
  16. return results
  17. return decorator

 paginate的items就是Pagination里的Model对象的集合,这些item直接用JSONEncoder序列化即可

  1. import datetime
  2. import decimal
  3. from flask.json import JSONEncoder as BaseJSONEncoder
  4. from stock_flask.models.base_model import BaseModel
  5. class JSONEncoder(BaseJSONEncoder):
  6. def default(self, o):
  7. if isinstance(o, datetime.datetime):
  8. return o.strftime('%Y-%m-%d %H:%M:%S')
  9. if isinstance(o, datetime.date):
  10. return o.strftime('%Y-%m-%d')
  11. if isinstance(o, datetime.time):
  12. return o.strftime('%H:%M:%S')
  13. if isinstance(o, decimal.Decimal):
  14. return float(o)
  15. if isinstance(o, BaseModel):
  16. return o.to_json(o)
  17. return super(JSONEncoder, self).default(o)

BaseModel继承自Model,并实现了to_json()方法

  1. from stock_flask.extensions import db
  2. class BaseModel(db.Model):
  3. @staticmethod
  4. def to_json(obj):
  5. res = {}
  6. for c in obj.__table__.columns:
  7. value = getattr(obj, c.name, '')
  8. res[c.name] = value
  9. return res

在实现paginate的方法上使用装饰器,并在视图函数输出结果时使用指定的JSONEncoder,即可使接口输出想要的json

 输出的效果:

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小丑西瓜9/article/detail/181081
推荐阅读
相关标签
  

闽ICP备14008679号