sqlalchemy查询结果转为json并通过restapi接口返回的解决方案

https://www.liaoxuefeng.com/wiki/1016959663602400/1017803857459008

def to_json(inst, cls):
d = dict()
‘‘‘
获取表里面的列并存到字典里面
‘‘‘
for c in cls.__table__.columns:
v = getattr(inst, c.name)
d[c.name] = v
return json.dumps(d)

class RFID(db.Model):
id = db.Column(db.Integer, primary_key=True)
node = db.Column(db.String(10))
card = db.Column(db.String(24))
timestamp = db.Column(db.DateTime, default=datetime.now)

@property
def serialize(self):
return to_json(self, self.__class__)


class Comment(db.Model):
__tablename__ = ‘t_comment‘
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
content = db.Column(db.Text, nullable=False)
create_time = db.Column(db.DateTime, nullable=False, default=datetime.now)
author_id = db.Column(db.Integer, db.ForeignKey(‘t_user.id‘))
question_id = db.Column(db.Integer, db.ForeignKey(‘t_question.id‘))

author = db.relationship(‘User‘, backref=db.backref(‘comments‘))
question = db.relationship(‘Question‘, backref=db.backref(‘comments‘, order_by=create_time.desc()))

def to_json(self):
dict = self.__dict__
if "_sa_instance_state" in dict:
del dict["_sa_instance_state"]
return dict


# rest api接口,并将查询结果转化为json
@app.route(‘/comments‘, methods=[‘GET‘])
def comments():
comments = db.session.query(Comment).all()
result = []
for comment in comments:
result.append(comment.to_json())
return jsonify(result), 200

from flask import Flask
from flask import jsonify
import json

app=Flask(__name__)
app.config[‘JSON_AS_ASCII‘] = False

# 随便定义个json字典
dic={"a":1,"b":2,"c":"你好"}
@app.route(‘/jsonify‘)
def jsonifys():
# Content-Type: application/json
return jsonify(dic)

@app.route(‘/jsondumps‘)
def jsondumps():
# Content-Type: text/html; charset=utf-8
return json.dumps(dic,ensure_ascii=False)

if __name__ == ‘__main__‘:
app.run(debug=True)

使用jsonify时响应的Content-Type字段值为application/json,

而使用json.dumps时该字段值为text/html。

sqlalchemy查询结果转为json并通过restapi接口返回的解决方案

上一篇:sql server异常抓包记录


下一篇:数据库