自定义 Marshmallow URLFor 中使用的 ID

Customising the ID used in Marshmallow URLFor

我正在使用 Sqlite 数据库和 flask、marshmallow、sqlalchemy 作为前端项目的 Web api。 我正在使用作为 blob 存储在数据库中的 UUID,并尝试在数据返回到调用代码时对数据进行样式化。 我可以使用 marshmallow 的 Function 字段在模型中返回时转换 Id,但是使用超链接,Id 仍然作为字节数组字符串输出:

class Item(Base):
    __tablename__ = 'Items'

    Id = Column(LargeBinary, primary_key=True)

    def __repr__(self):
        return '<Item {}>'.format(self.Name)

class ItemSchema(ma.Schema):
    Id = fields.Function(lambda obj: str(UUID(bytes=obj.Id)))
    _links = ma.Hyperlinks(
        {"url": ma.URLFor("item_detail", id="<Id>"), "collection": ma.URLFor("items")}
    )
    class Meta: 
        fields = ("_links", "Id")

有没有办法格式化在link中输出的? 即

{"url": ma.URLFor("item_detail", id="<str(UUID(bytes=Id))>"), "collection": ma.URLFor("items")}

这是当前的输出方式:

{"_links": {"url": "/api/items/b%27%5Cx86%5Cxacx__%5Cxf9%5Cxc2J%5Cx80a6%5Cxa7%5Cx95%5Cx10%5Cx91%5Cxff%27", "collection": "/api/items"}, "Id": "86ac785f-5ff9-c24a-8061-36a7951091ff"}

我希望它看起来像:

{"_links": {"url": "/api/items/86ac785f-5ff9-c24a-8061-36a7951091ff", "collection": "/api/items"}, "Id": "86ac785f-5ff9-c24a-8061-36a7951091ff"}

我希望 link 使用 UUID 格式,而不是字节数组。

我找到了解决这个问题的方法。这是模型设置而不是棉花糖。 由于数据库 was/is 将 pk 存储为 blob,我能够使用 SQLAlchemy_utils UUID 列,将二进制设置为 true,并且一切正常:

from sqlalchemy_utils import UUIDType
from uuid import UUID
....
Id = Column(UUIDType(binary=True), primary_key=True)