0

I am using a Sqlite database, and flask, marshmallow, sqlalchemy to serve as a web api for a front end project. I'm using a UUID stored as a blob in the database, and trying to stylise the data when its returned to the calling code. I can convert the Id when its returned in the model using marshmallow's Function field, but using the HyperLinks, the Id is still being output as a byte array string:

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

Is there a way to format the < Id > that is output in the links? i.e

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

Here's how it is currently output:

{"_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"}

I want it to look like:

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

I want the link to use the UUID format, not the byte array.

Marcus S
  • 103
  • 8

1 Answers1

0

I found out the way around this. It was with the model set up and not marshmallow. As the database was/is storing the pk as a blob, I was able to use SQLAlchemy_utils UUID column, setting the binary to true, and it all worked:

from sqlalchemy_utils import UUIDType
from uuid import UUID
....
Id = Column(UUIDType(binary=True), primary_key=True)
Marcus S
  • 103
  • 8