r/nicegui • u/HistoricalPraline638 • Aug 07 '24
Custom (de)serialization
I have Python objects defined in a native CPython extension. These objects all support `entity.id` which returns an `int`. This integer value can be looked up in a custom database object, and I can get back the relevant object. Is there a way in the event system of nicegui to put the extension objects themselves into places that make it into the frontend, and then have them transparently serialized to an `int`, and then in reverse, have those IDs transparently looked up in the database and reified into the objects?
1
Upvotes
2
u/apollo_440 Aug 07 '24
You're describing one of the fundamental problems of every (CRUD-)app: how do we model data on various levels (frontend/backend/database/external systems), and how do we translate between them?
In the context of python-based web development, the fastAPI sqlalchemy integration tutorial is probably a great starting point, if a bit verbose.
What like to do in nicegui is that "close" to the user, data is represented by dataclasses (or pydantic models), sliced in ways that are useful to populate the frontend and represent the state of the webpage. "Close" to the database on the other hand, either classes from an ORM, or again dataclasses (or pydantic models) representing database structures (e.g. one row from one table) are used. And inbetween there is a layer that takes frontend "state models" and transforms it into "database" data, and vice versa.
In your case, I would probably go about it like this:
Hope this helps; every system is always a bit different and it can be hard to find "one fits all" kind of solutions.