Flask_使用flask_marshmallow序列化数据

代码如下:

from flask import Flask
from flask_marshmallow import Marshmallow
from flask_sqlalchemy import SQLAlchemy
from marshmallow import fields

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123456@192.168.3.66:3306/tms?charset=utf8mb4"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

db = SQLAlchemy()
db.init_app(app)

ma = Marshmallow()
ma.init_app(app)


# ========================= 模型类 =========================================================
class User(db.Model):
    __tablename__ = 'admin_user'
    id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='用户ID')
    username = db.Column(db.String(20), comment='用户名')
    realname = db.Column(db.String(20), comment='真实名字')
    remark = db.Column(db.String(255), comment='备注')
    dept_id = db.Column(db.Integer, comment='部门id')


# ========================= 序列化类 =========================================================
class UserSchema(ma.Schema):
    userId = fields.Integer(attribute="id")     # 变量名称为序列化后的key名称,attribute为数据库的字段名称,若变量名称和数据库字段名称一致,可缺省attribute
    username = fields.Str()
    realname = fields.Str()


@app.route("/")
def index():
    users = db.session.query(User).all()
    print("序列化的模型类")
    print("入参数据", users)
    schema = UserSchema(many=True)
    ret = schema.dump(users)
    print("出参数据", ret)
    return ret


if __name__ == '__main__':
    app.run(debug=True, host="localhost", port=8000)

执行结果:

联表不知道怎么序列化,求大神告知~

posted @ 2023-04-01 22:24  码上测  阅读(125)  评论(0编辑  收藏  举报