[lib] Add HJSONResponse.

This commit is contained in:
Joël Maïzi 2020-08-05 12:58:05 +02:00
parent 446db4ee27
commit d164ad001a
1 changed files with 26 additions and 1 deletions

View File

@ -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)