Skip to content

Commit

Permalink
Switch from monty or orsjon for serialization
Browse files Browse the repository at this point in the history
  • Loading branch information
munrojm committed Jul 9, 2021
1 parent 8122d6b commit 6990c96
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 10 deletions.
17 changes: 9 additions & 8 deletions src/maggma/api/resource/read_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
from maggma.api.query_operator import PaginationQuery, QueryOperator, SparseFieldsQuery
from maggma.api.resource import Resource
from maggma.api.resource.utils import attach_query_ops
from maggma.api.utils import STORE_PARAMS, merge_queries
from maggma.api.utils import STORE_PARAMS, merge_queries, custom_serialization
from maggma.core import Store

from monty.serialization import MontyEncoder
import orjson


class ReadOnlyResource(Resource):
Expand All @@ -32,7 +33,7 @@ def __init__(
query: Optional[Dict] = None,
enable_get_by_key: bool = True,
enable_default_search: bool = True,
monty_encoded_response: bool = False,
custom_encoded_response: bool = False,
include_in_schema: Optional[bool] = True,
sub_path: Optional[str] = "/",
):
Expand All @@ -46,7 +47,7 @@ def __init__(
to allow user to define these on-the-fly.
enable_get_by_key: Enable default key route for endpoint.
enable_default_search: Enable default endpoint search behavior.
monty_encoded_response: Whether to use MontyEncoder and provide a direct FastAPI response.
custom_encoded_response: Whether to use ORJSON and provide a direct FastAPI response.
Note this will disable auto JSON serialization and response validation with the
provided model.
include_in_schema: Whether the endpoint should be shown in the documented schema.
Expand All @@ -59,7 +60,7 @@ def __init__(
self.versioned = False
self.enable_get_by_key = enable_get_by_key
self.enable_default_search = enable_default_search
self.monty_encoded_response = monty_encoded_response
self.custom_encoded_response = custom_encoded_response
self.include_in_schema = include_in_schema
self.sub_path = sub_path
self.response_model = Response[model] # type: ignore
Expand Down Expand Up @@ -138,9 +139,9 @@ async def get_by_key(

response = {"data": item}

if self.monty_encoded_response:
if self.custom_encoded_response:
response = BareResponse( # type: ignore
MontyEncoder().encode(response)
orjson.dumps(response, default=custom_serialization)
)

return response
Expand Down Expand Up @@ -195,9 +196,9 @@ async def search(**queries: Dict[str, STORE_PARAMS]) -> Dict:

response = {"data": data, "meta": {**meta.dict(), **operator_meta}}

if self.monty_encoded_response:
if self.custom_encoded_response:
response = BareResponse( # type: ignore
MontyEncoder().encode(response)
orjson.dumps(response, default=custom_serialization)
)

return response
Expand Down
7 changes: 7 additions & 0 deletions src/maggma/api/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import inspect
import sys
from typing import Any, Callable, Dict, List, Optional, Type
from bson.objectid import ObjectId

from monty.json import MSONable
from pydantic import BaseModel
Expand Down Expand Up @@ -161,3 +162,9 @@ def validate_monty(cls, v):
setattr(monty_cls, "validate_monty", classmethod(validate_monty))

return monty_cls


def custom_serialization(obj):
if isinstance(obj, ObjectId):
return str(obj)
raise TypeError
4 changes: 2 additions & 2 deletions tests/api/test_read_resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ def test_msonable(owner_store):


def test_get_by_key(owner_store):
endpoint = ReadOnlyResource(owner_store, Owner, monty_encoded_response=True)
endpoint = ReadOnlyResource(owner_store, Owner, custom_encoded_response=True)
app = FastAPI()
app.include_router(endpoint.router)

Expand Down Expand Up @@ -128,7 +128,7 @@ def search_helper(payload, base: str = "/?", debug=True) -> Response:
NumericQuery(model=Owner),
SparseFieldsQuery(model=Owner),
],
monty_encoded_response=True,
custom_encoded_response=True,
)
app = FastAPI()
app.include_router(endpoint.router)
Expand Down

0 comments on commit 6990c96

Please sign in to comment.