与marshmallow(反)序列化库集成的SQLAlchemy
项目描述
主页:https://marshmallow-sqlalchemy.readthedocs.io/
SQLAlchemy 与 marshmallow(反)序列化库的集成。
声明您的模型
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。
文档
项目链接
许可证
MIT 许可。有关更多详细信息,请参阅捆绑的 LICENSE 文件。
项目详情
下载文件
下载适合您平台的应用程序。如果您不确定要选择哪个,请了解有关 安装包 的更多信息。
源代码分发
marshmallow_sqlalchemy-1.1.0.tar.gz (49.5 kB 查看散列值)
构建分发
关闭
哈希值 for marshmallow_sqlalchemy-1.1.0-py3-none-any.whl
算法 | 散列摘要 | |
---|---|---|
SHA256 | cce261148e4c6ec4ee275f3d29352933380a1afa2fd3933f5e9ecd02fdc16ade |
|
MD5 | 33302a0bb235b8c37a394bd5ee9a44c8 |
|
BLAKE2b-256 | 0c47edc875e2f51923db12bf8c677595ca3c43bf7d9de8eaccd5d9bebc260c24 |