<s> from __future__ import unicode_literals <EOL> import json <EOL> from datetime import datetime <EOL> from google . appengine . ext import db <EOL> SIMPLE_TYPES = ( int , long , float , bool , dict , basestring , list , datetime ) <EOL> _ERROR_MSG = '<STR_LIT>' <EOL> class JSONSterlingSerializer ( object ) : <EOL> def __init__ ( self , explicit_none_check = False ) : <EOL> self . serialization_chain = [ ] <EOL> self . explicit_none_check = explicit_none_check <EOL> def add ( self , callable_serializer ) : <EOL> self . serialization_chain . append ( callable_serializer ) <EOL> return self <EOL> def __call__ ( self , serializable ) : <EOL> for serializer in self . serialization_chain : <EOL> result = serializer ( serializable ) <EOL> if ( ( not self . explicit_none_check and result ) or <EOL> ( self . explicit_none_check and result is not None ) ) : <EOL> return result <EOL> error_msg = _ERROR_MSG . format ( type ( serializable ) , repr ( serializable ) ) <EOL> raise TypeError ( error_msg ) <EOL> def handle_datetime ( serializable ) : <EOL> if hasattr ( serializable , '<STR_LIT>' ) : <EOL> return serializable . isoformat ( ) + '<STR_LIT>' <EOL> default_json_serializer = JSONSterlingSerializer ( ) <EOL> default_json_serializer . add ( handle_datetime ) <EOL> def to_json ( * args , ** kwargs ) : <EOL> is_xhr = kwargs . pop ( '<STR_LIT>' , None ) <EOL> indent = None if is_xhr else <NUM_LIT:2> <EOL> return json . dumps ( dict ( * args , ** kwargs ) , <EOL> indent = indent , <EOL> default = default_json_serializer ) <EOL> def to_dict ( model ) : <EOL> output = { } <EOL> for key , prop in model . properties ( ) . iteritems ( ) : <EOL> value = getattr ( model , key ) <EOL> if value is None or isinstance ( value , SIMPLE_TYPES ) : <EOL> output [ key ] = value <EOL> elif isinstance ( value , db . Model ) : <EOL> output [ key ] = to_dict ( value ) <EOL> else : <EOL> raise ValueError ( '<STR_LIT>' + repr ( prop ) ) <EOL> return output </s>
