refactored renders, added Datetime to typesystem
parent
3cd05013ab
commit
3a6ae5df43
@ -0,0 +1,17 @@
|
|||||||
|
import datetime
|
||||||
|
import dateutil
|
||||||
|
from apistar.typesystem import TypeSystemError
|
||||||
|
|
||||||
|
|
||||||
|
class Datetime(datetime.datetime):
|
||||||
|
native_type = datetime.datetime
|
||||||
|
|
||||||
|
def __new__(cls, *args, **kwargs) -> datetime:
|
||||||
|
if args and isinstance(args[0], cls.native_type):
|
||||||
|
return args[0]
|
||||||
|
if args and isinstance(args[0], str):
|
||||||
|
try:
|
||||||
|
return dateutil.parser.parse(args[0])
|
||||||
|
except ValueError:
|
||||||
|
raise TypeSystemError(cls=cls, code='type') from None
|
||||||
|
return cls.native_type(*args, **kwargs)
|
@ -1,10 +0,0 @@
|
|||||||
import datetime as dt
|
|
||||||
import decimal
|
|
||||||
|
|
||||||
|
|
||||||
def alchemyencoder(obj):
|
|
||||||
"""JSON encoder function with support for ISO 8601 datetime serialization and Decimal to float casting"""
|
|
||||||
if isinstance(obj, dt.datetime):
|
|
||||||
return obj.isoformat()
|
|
||||||
elif isinstance(obj, decimal.Decimal):
|
|
||||||
return float(obj)
|
|
@ -1,14 +0,0 @@
|
|||||||
import json
|
|
||||||
|
|
||||||
from cookie_api.models.util import alchemyencoder
|
|
||||||
|
|
||||||
from apistar import http
|
|
||||||
from apistar.renderers import Renderer
|
|
||||||
|
|
||||||
|
|
||||||
class JSONRenderer(Renderer):
|
|
||||||
media_type = 'application/json'
|
|
||||||
charset = None
|
|
||||||
|
|
||||||
def render(self, data: http.ResponseData) -> bytes:
|
|
||||||
return json.dumps(data, default=alchemyencoder).encode('utf-8')
|
|
@ -0,0 +1,23 @@
|
|||||||
|
import datetime as dt
|
||||||
|
import decimal
|
||||||
|
import json
|
||||||
|
|
||||||
|
from apistar import http
|
||||||
|
from apistar.renderers import Renderer
|
||||||
|
|
||||||
|
|
||||||
|
def extended_encoder(obj):
|
||||||
|
"""JSON encoder function with support for ISO 8601 datetime serialization and Decimal to float casting"""
|
||||||
|
if isinstance(obj, dt.datetime):
|
||||||
|
return obj.isoformat()
|
||||||
|
elif isinstance(obj, decimal.Decimal):
|
||||||
|
return float(obj)
|
||||||
|
|
||||||
|
|
||||||
|
class JSONRenderer(Renderer):
|
||||||
|
"""JSON Render with support for ISO 8601 datetime serialization and Decimal to float casting"""
|
||||||
|
media_type = 'application/json'
|
||||||
|
charset = None
|
||||||
|
|
||||||
|
def render(self, data: http.ResponseData) -> bytes:
|
||||||
|
return json.dumps(data, default=extended_encoder).encode('utf-8')
|
Loading…
Reference in New Issue