From d6075de2ebdc552551a7355a3a268ba157854891 Mon Sep 17 00:00:00 2001 From: Maxime Alves LIRMM Date: Wed, 23 Sep 2020 10:56:32 +0200 Subject: [PATCH] [lib][responses] add ORJSONResponse and update HJSONResponse --- halfapi/lib/responses.py | 36 ++++++++++-------------------------- 1 file changed, 10 insertions(+), 26 deletions(-) diff --git a/halfapi/lib/responses.py b/halfapi/lib/responses.py index 0ed3f64..9517baa 100644 --- a/halfapi/lib/responses.py +++ b/halfapi/lib/responses.py @@ -1,14 +1,12 @@ #!/usr/bin/env python3 # builtins -import numbers -import csv -from datetime import date -from io import TextIOBase, StringIO +import orjson from half_orm.null import NULL # asgi framework from starlette.responses import PlainTextResponse, Response, JSONResponse + __all__ = [ 'InternalServerErrorResponse', 'NotFoundResponse', @@ -44,26 +42,12 @@ class UnauthorizedResponse(Response): def __init__(self, *args, **kwargs): super().__init__(status_code = 401) -class HJSONResponse(JSONResponse): - def __init__(self, obj): - obj = self.__serialize(obj) - super().__init__( - content=obj, - status_code = 200) - def __serialize(self, obj): - if isinstance(obj, dict): - robj = dict() - for key, value in obj.items(): - robj[key] = self.__serialize(value) - return robj - if isinstance(obj, list): - robj = [] - for value in obj: - robj.append(self.__serialize(value)) - return robj - if isinstance(obj, numbers.Number) or isinstance(obj, str): - return obj - if obj == NULL: - return None - return str(obj) +class ORJSONResponse(JSONResponse): + def render(self, content: typ.Any) -> bytes: + return orjson.dumps(content) + + +class HJSONResponse(ORJSONResponse): + def render(self, content: typ.Generator): + return super().render([ elt for elt in content ])