Skip to content

Commit

Permalink
feat: serialize named tuples as dicts
Browse files Browse the repository at this point in the history
  • Loading branch information
maffettone committed Feb 20, 2025
1 parent 824f8ab commit 4ad2427
Showing 1 changed file with 10 additions and 4 deletions.
14 changes: 10 additions & 4 deletions databroker/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,10 @@
from tiled.client.utils import handle_error
from tiled.utils import safe_json_dump

from .common import BlueskyEventStreamMixin, BlueskyRunMixin, CatalogOfBlueskyRunsMixin
from .common import (BlueskyEventStreamMixin, BlueskyRunMixin,
CatalogOfBlueskyRunsMixin)
from .document import DatumPage, Descriptor, EventPage, Resource, Start, Stop
from .queries import PartialUID, RawMongo, ScanID
from .document import Start, Stop, Descriptor, EventPage, DatumPage, Resource


_document_types = {
"start": Start,
Expand Down Expand Up @@ -318,12 +318,18 @@ def v1(self):
self._v1 = Broker(self)
return self._v1

def _namedtuple_asdict_default(obj):
"""Convert NamedTuple to dict before serialization."""
if isinstance(obj, tuple) and hasattr(obj, "_asdict"): # NamedTuple check
return obj._asdict()
raise TypeError(f"Type {type(obj)} is not JSON serializable")

def post_document(self, name, doc):
link = self.item["links"]["self"].replace(
"/metadata", "/documents", 1
)
response = self.context.http_client.post(
link,
content=safe_json_dump({"name": name, "doc": doc})
content=safe_json_dump({"name": name, "doc": doc}, default=self._namedtuple_asdict_default)
)
handle_error(response)

0 comments on commit 4ad2427

Please sign in to comment.