Skip to main content

SQLAlchemy integration with the marshmallow (de)serialization library

Project description

Latest version Build status Documentation marshmallow 3 compatible code style: black

Homepage: https://marshmallow-sqlalchemy.readthedocs.io/

SQLAlchemy integration with the marshmallow (de)serialization library.

Declare your models

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)

Generate marshmallow schemas

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

You can automatically generate fields for a model’s columns using SQLAlchemyAutoSchema. The following schema classes are equivalent to the above.

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

Make sure to declare Models before instantiating Schemas. Otherwise sqlalchemy.orm.configure_mappers() will run too soon and fail.

(De)serialize your data

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

Get it now

pip install -U marshmallow-sqlalchemy

Requires Python >= 3.7, marshmallow >= 3.0.0, and SQLAlchemy >= 1.3.0.

Documentation

Documentation is available at https://marshmallow-sqlalchemy.readthedocs.io/ .

License

MIT licensed. See the bundled LICENSE file for more details.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

marshmallow-sqlalchemy-0.28.1.tar.gz (51.7 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

marshmallow_sqlalchemy-0.28.1-py2.py3-none-any.whl (16.0 kB view details)

Uploaded Python 2Python 3

File details

Details for the file marshmallow-sqlalchemy-0.28.1.tar.gz.

File metadata

  • Download URL: marshmallow-sqlalchemy-0.28.1.tar.gz
  • Upload date:
  • Size: 51.7 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/4.0.1 CPython/3.10.5

File hashes

Hashes for marshmallow-sqlalchemy-0.28.1.tar.gz
Algorithm Hash digest
SHA256 aa376747296780a56355e3067b9c8bf43a2a1c44ff985de82b3a5d9e161ca2b8
MD5 5e012b07ccf4ad67dbd3f38cc68cb1f4
BLAKE2b-256 eb963895bde2247fa653c36d887ff08e439665668aa7c991a3924ae199be88d6

See more details on using hashes here.

File details

Details for the file marshmallow_sqlalchemy-0.28.1-py2.py3-none-any.whl.

File metadata

File hashes

Hashes for marshmallow_sqlalchemy-0.28.1-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 dbb061c19375eca3a7d18358d2ca8bbaee825fc3000a3f114e2698282362b536
MD5 c2fe8c8f0f9b7acb7367dfa9ae9ca342
BLAKE2b-256 bef8b7ec99c9c2d5c42779d311010c024ff1224eb53b4ebfcc1de593a6f01390

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page