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)

执行结果:

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

源码等资料获取方法

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

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

相关推荐
海天一色y1 小时前
Pycharm(十六)面向对象进阶
ide·python·pycharm
??? Meggie1 小时前
【Python】保持Selenium稳定爬取的方法(防检测策略)
开发语言·python·selenium
Minyy111 小时前
SpringBoot程序的创建以及特点,配置文件,LogBack记录日志,配置过滤器、拦截器、全局异常
xml·java·spring boot·后端·spring·mybatis·logback
XIE3922 小时前
Browser-use使用教程
python
酷爱码3 小时前
如何通过python连接hive,并对里面的表进行增删改查操作
开发语言·hive·python
画个大饼3 小时前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
蹦蹦跳跳真可爱5893 小时前
Python----深度学习(基于深度学习Pytroch簇分类,圆环分类,月牙分类)
人工智能·pytorch·python·深度学习·分类
MinggeQingchun6 小时前
Python - 爬虫-网页解析数据-库lxml(支持XPath)
爬虫·python·xpath·lxml
Python自动化办公社区7 小时前
Python 3.14:探索新版本的魅力与革新
开发语言·python
weixin_贾8 小时前
最新AI-Python机器学习与深度学习技术在植被参数反演中的核心技术应用
python·机器学习·植被参数·遥感反演