Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: serialize named tuples as dicts #837

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,24 @@ def v1(self):
self._v1 = Broker(self)
return self._v1

@staticmethod
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})
)
try:
response = self.context.http_client.post(
link, content=safe_json_dump({"name": name, "doc": doc}, default=self._namedtuple_asdict_default)
)
except TypeError as e:
if "got an unexpected keyword argument" in str(e):
response = self.context.http_client.post(
link, content=safe_json_dump({"name": name, "doc": doc})
)
else:
raise
handle_error(response)
2 changes: 1 addition & 1 deletion databroker/client.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# This module is now a back-compat shim. The objects are defined in a
# separate package, bluesky_tiled_plugins, that resides in the same
# git repository as databroker.
from bluesky_tiled_plugins import BlueskyRun, CatalogOfBlueskyRuns, BlueskyEventStream # noqa: F401
from bluesky_tiled_plugins import BlueskyEventStream, BlueskyRun, CatalogOfBlueskyRuns # noqa: F401
Loading