如何用marshmallow
和flask-marshmallow
来序列化Postgres的UUID列类型?
这是示例模型,请注意Postgres的UUID方言:
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)
现在,Marsmallow的模型架构非常简单,直接来自example:
from marshmallow_sqlalchemy import ModelSchema
class AuthorSchema(ModelSchema):
class Meta:
model = Author
所有序列化失败:
author = Author(name="Chuck Paluhniuk")
author_schema = AuthorSchema()
session.add(author)
session.commit()
dump_data = author_schema.dump(author).data
这将返回:
TypeError:UUID类型的对象不可JSON序列化
将UUID解析为字符串的最佳方法是什么?
一种方法是在模型架构中包含post_dump
:
@post_dump()
def __post_dump(self, data):
data['id'] = str(data['id'])
但是我更喜欢UUID的通用方法,因为我使用了很多方法。