跳转到主要内容

与marshmallow(反)序列化库集成的SQLAlchemy

项目描述

Latest version Build status Documentation marshmallow 3 compatible

主页:https://marshmallow-sqlalchemy.readthedocs.io/

SQLAlchemymarshmallow(反)序列化库的集成。

声明您的模型

import sqlalchemy as sa
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker, relationship, backref

engine = sa.create_engine("sqlite:///:memory:")
session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()


class Author(Base):
    __tablename__ = "authors"
    id = sa.Column(sa.Integer, primary_key=True)
    name = sa.Column(sa.String, nullable=False)

    def __repr__(self):
        return "<Author(name={self.name!r})>".format(self=self)


class Book(Base):
    __tablename__ = "books"
    id = sa.Column(sa.Integer, primary_key=True)
    title = sa.Column(sa.String)
    author_id = sa.Column(sa.Integer, sa.ForeignKey("authors.id"))
    author = relationship("Author", backref=backref("books"))


Base.metadata.create_all(engine)

生成marshmallow架构

from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field


class AuthorSchema(SQLAlchemySchema):
    class Meta:
        model = Author
        load_instance = True  # Optional: deserialize to model instances

    id = auto_field()
    name = auto_field()
    books = auto_field()


class BookSchema(SQLAlchemySchema):
    class Meta:
        model = Book
        load_instance = True

    id = auto_field()
    title = auto_field()
    author_id = auto_field()

您可以使用< cite>SQLAlchemyAutoSchema自动为模型列生成字段。以下架构类与上述等价。

from marshmallow_sqlalchemy import SQLAlchemyAutoSchema


class AuthorSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Author
        include_relationships = True
        load_instance = True


class BookSchema(SQLAlchemyAutoSchema):
    class Meta:
        model = Book
        include_fk = True
        load_instance = True

确保在实例化 Schema 之前声明 Models。否则,sqlalchemy.orm.configure_mappers() 将过早运行并失败。

(反)序列化数据

author = Author(name="Chuck Paluhniuk")
author_schema = AuthorSchema()
book = Book(title="Fight Club", author=author)
session.add(author)
session.add(book)
session.commit()

dump_data = author_schema.dump(author)
print(dump_data)
# {'id': 1, 'name': 'Chuck Paluhniuk', 'books': [1]}

load_data = author_schema.load(dump_data, session=session)
print(load_data)
# <Author(name='Chuck Paluhniuk')>

立即获取

pip install -U marshmallow-sqlalchemy

需要 Python >= 3.8, marshmallow >= 3.18.0, 和 SQLAlchemy >= 1.4.40。

文档

文档可在 https://marshmallow-sqlalchemy.readthedocs.io/ 查找。

许可证

MIT 许可。有关更多详细信息,请参阅捆绑的 LICENSE 文件。

项目详情


发布历史 发布通知 | RSS 源

下载文件

下载适合您平台的应用程序。如果您不确定要选择哪个,请了解有关 安装包 的更多信息。

源代码分发

marshmallow_sqlalchemy-1.1.0.tar.gz (49.5 kB 查看散列值)

上传时间 源代码

构建分发

marshmallow_sqlalchemy-1.1.0-py3-none-any.whl (14.4 kB 查看散列值)

上传时间 Python 3

由以下提供支持