From d164ad001a906d284f5346a5ab19fd2973b52539 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=ABl=20Ma=C3=AFzi?= Date: Wed, 5 Aug 2020 12:58:05 +0200 Subject: [PATCH] [lib] Add HJSONResponse. --- halfapi/lib/responses.py | 27 ++++++++++++++++++++++++++- 1 file changed, 26 insertions(+), 1 deletion(-) diff --git a/halfapi/lib/responses.py b/halfapi/lib/responses.py index 8652bac..0ed3f64 100644 --- a/halfapi/lib/responses.py +++ b/halfapi/lib/responses.py @@ -1,11 +1,13 @@ #!/usr/bin/env python3 # builtins +import numbers import csv from datetime import date from io import TextIOBase, StringIO +from half_orm.null import NULL # asgi framework -from starlette.responses import PlainTextResponse, Response +from starlette.responses import PlainTextResponse, Response, JSONResponse __all__ = [ 'InternalServerErrorResponse', @@ -42,3 +44,26 @@ 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)