Python Flask + vue前后端分离中使用 SQLAlchemy查询mysql结果转换为Json格式输出
最近在做前后面分离项目时,使用SQLAlchemy查询mysql数据时,使用flask自带的jsonify对查询到的结果进行格式化给前端时
程序一直在报TypeError: Object of type EmployeeModel is not JSON serializable
这是SQLAlchemy模型:
from applications.extensions import db from datetime import datetime # 员工信息 class EmployeeModel(db.Model): __tablename__ = "employee_info" id = db.Column(db.Integer, primary_key=True, autoincrement=True) employee_name = db.Column(db.String(100), nullable=False) # 名称 employee_gend = db.Column(db.String(100), nullable=False) # 性别 employee_nation = db.Column(db.String(100), nullable=False) # 民族 employee_phone = db.Column(db.String(100), nullable=False) # 电话 employee_birthday = db.Column(db.String(100), nullable=False) # 生日 employee_id_card = db.Column(db.String(100), nullable=False) # 身份证号码 employee_bank_card = db.Column(db.String(100), nullable=False) # 银行卡号码 employee_bank = db.Column(db.String(100), nullable=False) # 所属银行 employee_address = db.Column(db.String(300), nullable=False) # 地址 employee_occupation = db.Column(db.String(100), nullable=False) # 职业 employee_post = db.Column(db.String(100), nullable=False) # 职务 employee_content = db.Column(db.Text, nullable=False) # 其他 create_time = db.Column(db.DateTime, default=datetime.now) # 创建时间
这是视图模型:
from flask import Blueprint, jsonify, request from applications.models.employee import EmployeeModel from applications.extensions import db bp = Blueprint("employee", __name__, url_prefix="/employee") @bp.get("/") def get_employee_info(): result = { "code": "200", "msg": "信息查询成功!", "data": None } employee_info = EmployeeModel.query.order_by(EmployeeModel.create_time.desc()).all() print(type(employee_info),employee_info[1].create_time) result['data'] = employee_info return jsonify(result)
请求之后:
首先要搞清楚为什么会报这种错误,
我使用type()去打印查询的结果时,发现它是一个list包含的对象,使用len()方法计算它的长度时候会失败,
当再使用jsonify()方法处理它时,就会报以
上错误,我需要将这个对象转换成一个可以迭代list
网上查询很多资料后,总结有3条
1,修改json内的解释器,
对于直接修改系统文件,就算真能解决也不适合,毕竟我们代码在要很多机器上跑,不可能一台台机器修改
2,引用第三方插件或库
这个方法也不建议使用,毕竟依赖多了,问题也就多了
3,对数据模型添加处理方法,将查询结果直接引用该方法
这种方法方便快捷,容易理解,又不会对其他造成影响,所以是首选项
from applications.extensions import db from datetime import datetime # 员工信息 class EmployeeModel(db.Model): __tablename__ = "employee_info" id = db.Column(db.Integer, primary_key=True, autoincrement=True) employee_name = db.Column(db.String(100), nullable=False) # 名称 employee_gend = db.Column(db.String(100), nullable=False) # 性别 employee_nation = db.Column(db.String(100), nullable=False) # 民族 employee_phone = db.Column(db.String(100), nullable=False) # 电话 employee_birthday = db.Column(db.String(100), nullable=False) # 生日 employee_id_card = db.Column(db.String(100), nullable=False) # 身份证号码 employee_bank_card = db.Column(db.String(100), nullable=False) # 银行卡号码 employee_bank = db.Column(db.String(100), nullable=False) # 所属银行 employee_address = db.Column(db.String(300), nullable=False) # 地址 employee_occupation = db.Column(db.String(100), nullable=False) # 职业 employee_post = db.Column(db.String(100), nullable=False) # 职务 employee_content = db.Column(db.Text, nullable=False) # 其他 create_time = db.Column(db.DateTime, default=datetime.now) # 创建时间 # 像模型字段处理成list def to_dict(self): return { "employee_name": self.employee_name, # 名称 "employee_gend": self.employee_gend, # 性别 "employee_nation": self.employee_nation, # 民族 "employee_phone": self.employee_phone, # 电话 "employee_birthday": self.employee_birthday, # 生日 "employee_id_card": self.employee_id_card, # 身份证号码 "employee_bank_card": self.employee_bank_card, # 银行卡号码 "employee_bank": self.employee_bank, # 所属银行 "employee_address": self.employee_address, # 地址 "employee_occupation": self.employee_occupation, # 职业 "employee_post": self.employee_post, # 职务 "employee_content": self.employee_content, # 其他 "create_time": self.create_time # 创建时间 }
在视图方法中引用上面添加的方法
from flask import Blueprint, jsonify, request from applications.models.employee import EmployeeModel from applications.extensions import db bp = Blueprint("employee", __name__, url_prefix="/employee") @bp.get("/") def get_employee_info(): result = { "code": "200", "msg": "信息查询成功!", "data": None } employee_info = EmployeeModel.query.order_by(EmployeeModel.create_time.desc()).all() employee_info_list = [] print(type(employee_info),employee_info[1].create_time) for item in employee_info: employee_info_list.append(item.to_dict()) result['data'] = employee_info_list return jsonify(result)
最后,完美解决查询结果json格式化