Flask_使用flask_marshmallow序列化数据

代码如下:

python 复制代码
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:[email protected]: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)

执行结果:

联表序列化,后续研究研究在给大家说说。

源码等资料获取方法

各位想获取源码等教程资料的朋友请 点赞 + 评论 + 收藏 ,三连!

三连之后我会在评论区挨个私信发给你们~

相关推荐
Stara05111 小时前
基于多头自注意力机制(MHSA)增强的YOLOv11主干网络—面向高精度目标检测的结构创新与性能优化
人工智能·python·深度学习·神经网络·目标检测·计算机视觉·yolov11
源码方舟1 小时前
SpringBoot + Shiro + JWT 实现认证与授权完整方案实现
java·spring boot·后端
那雨倾城2 小时前
使用 OpenCV 将图像中标记特定颜色区域
人工智能·python·opencv·计算机视觉·视觉检测
LuckyTHP4 小时前
java 使用zxing生成条形码(可自定义文字位置、边框样式)
java·开发语言·python
热河暖男4 小时前
【实战解决方案】Spring Boot+Redisson构建高并发Excel导出服务,彻底解决系统阻塞难题
spring boot·后端·excel
mahuifa6 小时前
(7)python开发经验
python·qt·pyside6·开发经验
学地理的小胖砸7 小时前
【Python 操作 MySQL 数据库】
数据库·python·mysql
安迪小宝7 小时前
6 任务路由与负载均衡
运维·python·celery
Blossom.1187 小时前
使用Python实现简单的人工智能聊天机器人
开发语言·人工智能·python·低代码·数据挖掘·机器人·云计算
lisw057 小时前
Python高级进阶:Vim与Vi使用指南
python·vim·excel