333 else: |
333 else: |
334 |
334 |
335 class CubicWebJsonEncoder(json.JSONEncoder): |
335 class CubicWebJsonEncoder(json.JSONEncoder): |
336 """define a json encoder to be able to encode yams std types""" |
336 """define a json encoder to be able to encode yams std types""" |
337 |
337 |
338 # _iterencode is the only entry point I've found to use a custom encode |
|
339 # hook early enough: .default() is called if nothing else matched before, |
|
340 # .iterencode() is called once on the main structure to encode and then |
|
341 # never gets called again. |
|
342 # For the record, our main use case is in FormValidateController with: |
|
343 # json.dumps((status, args, entity), cls=CubicWebJsonEncoder) |
|
344 # where we want all the entity attributes, including eid, to be part |
|
345 # of the json object dumped. |
|
346 # This would have once more been easier if Entity didn't extend dict. |
|
347 def _iterencode(self, obj, markers=None): |
|
348 if hasattr(obj, '__json_encode__'): |
|
349 obj = obj.__json_encode__() |
|
350 return json.JSONEncoder._iterencode(self, obj, markers) |
|
351 |
|
352 def default(self, obj): |
338 def default(self, obj): |
|
339 if hasattr(obj, 'eid'): |
|
340 d = obj.cw_attr_cache.copy() |
|
341 d['eid'] = obj.eid |
|
342 return d |
353 if isinstance(obj, datetime.datetime): |
343 if isinstance(obj, datetime.datetime): |
354 return obj.strftime('%Y/%m/%d %H:%M:%S') |
344 return obj.strftime('%Y/%m/%d %H:%M:%S') |
355 elif isinstance(obj, datetime.date): |
345 elif isinstance(obj, datetime.date): |
356 return obj.strftime('%Y/%m/%d') |
346 return obj.strftime('%Y/%m/%d') |
357 elif isinstance(obj, datetime.time): |
347 elif isinstance(obj, datetime.time): |