Start working on the non-trivial types handling

This commit is contained in:
Christophe de Vienne
2011-09-19 22:39:02 +02:00
parent cc4dd1cbf8
commit eebff1a28a
2 changed files with 34 additions and 1 deletions

View File

@@ -1,11 +1,29 @@
import base64
from wsme.rest import RestProtocol
from wsme.controller import register_protocol
import wsme.types
try:
import simplejson as json
except ImportError:
import json
def prepare_encode(value, datatype):
if datatype in wsme.types.pod_types:
return value
if datatype in wsme.types.structured_types:
d = dict()
for name, datatype, mandatory in wsme.types.list_attributes(value):
d[name] = prepare_encode(getattr(value, name), datatype)
return d
if datatype in wsme.types.dt_types:
return value.isoformat()
if datatype is wsme.types.binary:
return base64.encode()
class RestJsonProtocol(RestProtocol):
name = 'REST+Json'
dataformat = 'json'
@@ -16,7 +34,7 @@ class RestJsonProtocol(RestProtocol):
return kw
def encode_result(self, result, return_type):
return json.dumps({'result': result})
return json.dumps({'result': prepare_encode(result, return_type)})
def encode_error(self, errordetail):
return json.dumps(errordetail)

15
wsme/types.py Normal file
View File

@@ -0,0 +1,15 @@
import datetime
import decimal
binary = object()
pod_types = [str, unicode, int, float, bool]
dt_types = [datetime.date, datetime.time, datetime.datetime]
extra_types = [binary, decimal.Decimal]
native_types = pod_types + dt_types + extra_types
structured_types = []
def register_type(class_):
structured_types.append(class_)