From d21ee175e9504e99778a58770b08e3281deed5b5 Mon Sep 17 00:00:00 2001 From: Maxime Alves LIRMM Date: Thu, 14 Jan 2021 10:55:02 +0100 Subject: [PATCH] [responses] cast special types in ORJSONResponse --- halfapi/__init__.py | 2 +- halfapi/lib/responses.py | 14 +++++++++++++- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/halfapi/__init__.py b/halfapi/__init__.py index f42d8de..6ae62e1 100644 --- a/halfapi/__init__.py +++ b/halfapi/__init__.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -__version__ = '0.3.1' +__version__ = '0.4.1' def version(): return f'HalfAPI version:{__version__}' diff --git a/halfapi/lib/responses.py b/halfapi/lib/responses.py index 6c6cde0..4ab33f8 100644 --- a/halfapi/lib/responses.py +++ b/halfapi/lib/responses.py @@ -1,5 +1,6 @@ #!/usr/bin/env python3 # builtins +import decimal import typing as typ import orjson @@ -47,7 +48,7 @@ class UnauthorizedResponse(Response): class ORJSONResponse(JSONResponse): def __init__(self, content, default=None, **kwargs): - self.default = default + self.default = default if default is not None else ORJSONResponse.default_cast super().__init__(content, **kwargs) def render(self, content: typ.Any) -> bytes: @@ -55,6 +56,17 @@ class ORJSONResponse(JSONResponse): option=orjson.OPT_NON_STR_KEYS, default=self.default) + @staticmethod + def default_cast(x): + types = { + decimal.Decimal + } + + if type(x) not in types: + raise TypeError('Type is not handled in ORJSONResponse') + + return str(x) + class HJSONResponse(ORJSONResponse): def render(self, content: typ.Generator):