选择flask的序列化与反序列化
如果不喜欢flask resfulapi 的话可以尝试这几个库,序列化反序列化同Django类似
- marshmallow
- marshmallow-sqlalchemy
本文仅部分用法实例,更详细请见官方文档连接
marshmallow
marshmallow-sqlalchemy
安装
pip install marshmallow
pip install marshmallow-sqlalchemy
用法
模型类:
# models.py
from app import db
class Book(db.models):
__tablename__ = 'books'
id = db.Column(db.String(20), primary_key=True, default=getStrId)
code = db.Column(db.String(5))
number = db.Column(db.Integer())
name = db.Column(db.String(50))
createTime = db.Column(db.DateTime, server_default=db.FetchedValue())
序列化器:
# serializer.py
from models import Book
from marshmallow import EXCLUDE, validate, fields
from marshmallow_sqlalchemy import SQLAlchemyAutoSchema
# SQLAlchemyAutoSchema 会自动映射数据库列和字段
class BookSerializer(SQLAlchemyAutoSchema):
# 关于元类的更多字段请参考: https://marshmallow.readthedocs.io/en/stable/api_reference.html#marshmallow.Schema.Meta
class Meta:
model = Book # 模型类
ordered = True # 是否排序
include_fk = True #是否包含外键
unknown = EXCLUDE # 未知字段序列化选项
exclude = ("name",) # 序列化不需要的字段 反之对应include
number = fields.fields.Str() # 自定义映射类型 num是int类型序列化成string
id = fields.fields.String(validate=validate.Length(equal=19)) # 校验器 反序列化时id的长度要登录19位
视图层:
# view.py
from flask import views,jsonify
from models import Book
from serializer import BookSerializer
class BookViews(views.MethodView):
def get(self,id):
try:
book = Book.query.filter(Area.id == id).first()
resp_data = BookSerializer().dump(book)
# 序列化多个 加上many=True即可
# books = Book.query.filter(Area.id == id).all()
# resp_data = BookSerializer().dump(books, many=True)
return jsonify(code=0, success=True, msg=None, data=resp_data)
except Exception as e:
return jsonify(code=1, success=False, msg=str(e), data=None)