[lib][responses] add ORJSONResponse and update HJSONResponse

This commit is contained in:
Maxime Alves LIRMM 2020-09-23 10:56:32 +02:00
parent 39d455b682
commit d6075de2eb
1 changed files with 10 additions and 26 deletions

View File

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