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, auto_field


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.6, marshmallow >= 2.15.2, and SQLAlchemy >= 1.2.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.23.0.tar.gz (53.6 kB view details)

Uploaded Source

Built Distribution

marshmallow_sqlalchemy-0.23.0-py2.py3-none-any.whl (18.4 kB view details)

Uploaded Python 2 Python 3

File details

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

File metadata

  • Download URL: marshmallow-sqlalchemy-0.23.0.tar.gz
  • Upload date:
  • Size: 53.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.1.3 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.7.6

File hashes

Hashes for marshmallow-sqlalchemy-0.23.0.tar.gz
Algorithm Hash digest
SHA256 3247e41e424146340b03a369f2b7c6f0364477ccedc4e2481e84d5f3a8d3c67f
MD5 23d834d359c16f50b27e198ea35591ed
BLAKE2b-256 883b8038f41b1ba2159aac853b55491d3bd076f5d1b0aba8529cc762296cdbed

See more details on using hashes here.

Provenance

File details

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

File metadata

  • Download URL: marshmallow_sqlalchemy-0.23.0-py2.py3-none-any.whl
  • Upload date:
  • Size: 18.4 kB
  • Tags: Python 2, Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/3.1.1 pkginfo/1.5.0.1 requests/2.23.0 setuptools/46.1.3 requests-toolbelt/0.9.1 tqdm/4.45.0 CPython/3.7.6

File hashes

Hashes for marshmallow_sqlalchemy-0.23.0-py2.py3-none-any.whl
Algorithm Hash digest
SHA256 dbbe51d28bb28e7ee2782e51310477f7a2c5a111a301f6dd8e264e11ab820427
MD5 5276c8d25363ebf471935ca508ba988c
BLAKE2b-256 80b88419ae927fbd16bced8eb0640a171931260857efbf3b4acbadaa71400190

See more details on using hashes here.

Provenance

Supported by

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