mongkok / fastapi-debug-toolbar

A debug toolbar for FastAPI.
https://fastapi-debug-toolbar.domake.io
BSD 3-Clause "New" or "Revised" License
140 stars 14 forks source link

Ability to parse UUID #15

Closed deby22 closed 1 year ago

deby22 commented 2 years ago

https://github.com/mongkok/fastapi-debug-toolbar/blob/3552b0bbb8e1a86a4f5eaaf214e6916d52c941ef/debug_toolbar/panels/sql.py#L120-L121

Using UUID field raise an exception

*** TypeError: Object of type UUID is not JSON serializable

I suggest, adding UUID serialization, by cast to str

if isinstance(obj, UUID):
    return str(obj)

Or allow setting encoder on json.dumps method

florimondmanca commented 2 years ago

For anyone finding this issue, I bumped into the same situation and managed to find a workaround using FastAPI's jsonable_encoder:

from debug_toolbar.panels.sqlalchemy import SQLAlchemyPanel as Base
from fastapi.encoders import jsonable_encoder

class SQLAlchemyPanel(Base):
    def after_execute(self, *args) -> None:  # type: ignore
        # HACK: base SQL panel calls json.dumps(parameters) at some point.
        # Ensure values such as UUIDs can be dumped.
        parameters = args[3]
        args = (*args[:3], jsonable_encoder(parameters), *args[4:])
        return super().after_execute(*args)

It can then be used by passing panels=["path.to.panels.SQLAlchemyPanel"].

Not sure if this should be done by default.

mongkok commented 1 year ago

Hey @deby22 , issue is fixed using jsonable_encoder() as suggested by @florimondmanca , see #23 and v0.3.0.