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: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)

执行结果:

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

源码等资料获取方法

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

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

相关推荐
AI_56781 天前
Selenium+Python可通过 元素定位→操作模拟→断言验证 三步实现Web自动化测试
服务器·人工智能·python
蒜香拿铁1 天前
【第三章】python算数运算符
python
浮尘笔记1 天前
Go语言临时对象池:sync.Pool的原理与使用
开发语言·后端·golang
52Hz1181 天前
力扣73.矩阵置零、54.螺旋矩阵、48.旋转图像
python·算法·leetcode·矩阵
梦梦代码精1 天前
BuildingAI vs Dify vs 扣子:三大开源智能体平台架构风格对比
开发语言·前端·数据库·后端·架构·开源·推荐算法
weixin_462446231 天前
Python 使用 openpyxl 从 URL 读取 Excel 并获取 Sheet 及单元格样式信息
python·excel·openpyxl
REDcker1 天前
RESTful API设计规范详解
服务器·后端·接口·api·restful·博客·后端开发
毕设源码-钟学长1 天前
【开题答辩全过程】以 基于Python的健康食谱规划系统的设计与实现为例,包含答辩的问题和答案
开发语言·python
百***78751 天前
Grok-4.1技术深度解析:双版本架构突破与Python API快速集成指南
大数据·python·架构
2501_942191771 天前
基于YOLO11-HSFPN的数字检测与识别模型实现详解
python