Skip to content

Commit

Permalink
Experimental use of orjson to fasten json serialization (test on chan…
Browse files Browse the repository at this point in the history
…nel histogram bounds)

See tiangolo/fastapi#2615
  • Loading branch information
urubens committed Jan 6, 2022
1 parent 61b9ee0 commit 9d9728f
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 4 deletions.
7 changes: 4 additions & 3 deletions pims/api/histograms.py
Expand Up @@ -242,7 +242,8 @@ def show_channels_histogram(

@router.get(
'/image/{filepath:path}/histogram/per-channels/bounds',
tags=api_tags, response_model=ChannelsHistogramInfoCollection
tags=api_tags, response_model=ChannelsHistogramInfoCollection,
response_class=CustomOrJsonResponse
)
def show_channels_histogram_bounds(
path: Path = Depends(imagepath_parameter),
Expand All @@ -266,14 +267,14 @@ def show_channels_histogram_bounds(
for channel, bounds in zip(channels, channels_bounds):
mini, maxi = bounds
hist_info.append(
ChannelHistogramInfo(
dict(
channel=channel, type=htype,
color=in_image.channels[channel].hex_color,
minimum=mini, maximum=maxi
)
)

return response_list(hist_info)
return CustomOrJsonResponse(response_list(hist_info))


@router.get(
Expand Down
17 changes: 16 additions & 1 deletion pims/api/utils/response.py
Expand Up @@ -12,9 +12,11 @@
# * See the License for the specific language governing permissions and
# * limitations under the License.
import logging
from typing import Optional
from typing import Any, Optional

import orjson
from cytomine.models import Model
from fastapi.responses import ORJSONResponse
from pint import Quantity

log = logging.getLogger("pims")
Expand Down Expand Up @@ -66,3 +68,16 @@ def serialize_cytomine_model(o):
return d
log.warning(f"The object {o} is not a Cytomine model and is thus not serialized.")
return o


class CustomOrJsonResponse(ORJSONResponse):
def render(self, content: Any) -> bytes:
assert orjson is not None, "orjson must be installed to use ORJSONResponse"

def default(obj):
""" custom parser for orjson (usually named default) """
raise TypeError

return orjson.dumps(
content, option=orjson.OPT_SERIALIZE_NUMPY, default=default
)
2 changes: 2 additions & 0 deletions requirements.txt
Expand Up @@ -123,6 +123,8 @@ numpy==1.21.4
# zarr
opencv-python-headless==4.5.4.60
# via cytomine-python-client
orjson==3.6.5
# via pims (setup.py)
packaging==21.3
# via
# matplotlib
Expand Down
1 change: 1 addition & 0 deletions setup.py
Expand Up @@ -37,6 +37,7 @@
'uvicorn[standard]>=0.13.4',
'fastapi>=0.65.1',
'pydantic>=1.8.2',
'orjson>=3.6.5',
'rich>=10.2.2',
'python-dotenv>=0.17.1',
'python-multipart>=0.0.5',
Expand Down

0 comments on commit 9d9728f

Please sign in to comment.