Serialize UUID's with Marshmallow SQLAlchemy

Viewed 1612

How can I make marshmallow with flask-marshmallow to serialize Postgres' UUID column types?

This is the example model, note the UUID dialect of Postgres:

import uuid
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import scoped_session, sessionmaker

engine = create_engine('postgresql://postgres:postgres@postgres/author_db')
session = scoped_session(sessionmaker(bind=engine))
Base = declarative_base()


class Author(Base):
    __tablename__ = "authors"
    id = Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4)
    name = Column(String)


Base.metadata.create_all(engine)

Now, the Marsmallow's Model Schema is straightforward, directly from the example:

from marshmallow_sqlalchemy import ModelSchema

class AuthorSchema(ModelSchema):
    class Meta:
        model = Author

All serialization fails:

author = Author(name="Chuck Paluhniuk")
author_schema = AuthorSchema()
session.add(author)
session.commit()
dump_data = author_schema.dump(author).data

This will return:

TypeError: Object of type UUID is not JSON serializable

What is best way to parse UUID's as strings?

One way is to include a post_dump to the Model Schema:

@post_dump()
def __post_dump(self, data):
    data['id'] = str(data['id'])

But I prefer a more general approach to UUID's, because I use a lot of them.

0 Answers
Related