1、模型转Json时需要对一些特殊格式进行处理 比如金额(decimal)、和时间(datetime)

import json
import datetime
from decimal import Decimal,getcontext

class DateEncoder(json.JSONEncoder):
    def default(self, obj):
        """
        重新 JSONEncoder 转换方式
        :param obj: 
        :return: 
        """
        if isinstance(obj, Decimal):
            return float(obj)
        elif isinstance(obj, datetime.datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, datetime.date):
            return obj.strftime("%Y-%m-%d")
        else:
            return json.JSONEncoder.default(self, obj)

2、统一模型转换Json格式,一般给前端的有三个字段,code:返回值代码 标识返回数据的状态,msg:返回提示信息,data:返回的数据结果

class ResultModel():
    def __init__(self,code=0,msg="success",data=None):
        """
        :param code: 0 成功,1 失败
        :param msg: 原因说明
        :param data: 请求结果
        """
        self.code = code
        self.msg = msg

        is_list = data.__class__ == [].__class__
        is_set = data.__class__ == set().__class__
        if(is_set or is_list):
            sub = []
            for item in data:
                a = self.to_dict(item)
                sub.append(a)
            self.data = sub
        else:
            self.data = data

    def to_json(self):
        """
        模型转换为 json字符串,DateEncoder自定义转换模式
        :return: 
        """
        return json.dumps(obj=self.__dict__,ensure_ascii=False,cls=DateEncoder)

    def to_dict(self,item):
        """
        字典转换
        :param item: 
        :return: 
        """
        dict = {}
        dict.update(item.__dict__)
        return dict

 

4、调用 提供给web端,用tornado框架 举例

t = tsql()
class webHandler(tornado.web.RequestHandler):
    @tornado.web.authenticated
    def get(self, *args, **kwargs):
        try:
            data = t.selectdata()
            _re = ResultModel(data=data)
            self.write(_re.to_json())
        except Exception as e:
            _re = ResultModel(code=1,msg=str(e.args))
            self.write(_re.to_json())

5、_re.to_josn() 结果

{
 "code": 0, 
 "data": [{"price": 22.0, "id": 1, "createtime": "2020-01-07 21:46:34"}, 
      {"price": 1234567890.22, "id": 2, "createtime": "2020-01-07 21:46:57"}, 
      {"price": 10.0, "id": 3, "createtime": "2020-01-08 03:12:56"}, 
      {"price": 10.23, "id": 4, "createtime": "2020-01-08 03:15:52"},
      {"price": 10.24, "id": 5, "createtime": "2020-01-08 03:16:03"}, 
      {"price": 10.24, "id": 6, "createtime": "2020-01-08 03:18:49"}], 
 "msg": "success"
}