Changeset - e14ae8437548
[Not reviewed]
beta
0 2 0
Marcin Kuzminski - 14 years ago 2012-03-21 20:54:30
marcin@python-works.com
extended JSON encoder to use __json__ method if available
2 files changed with 16 insertions and 3 deletions:
0 comments (0 inline, 0 general)
rhodecode/lib/compat.py
Show inline comments
 
@@ -31,47 +31,57 @@ from rhodecode import __platform__, PLAT
 

	
 
#==============================================================================
 
# json
 
#==============================================================================
 

	
 

	
 
def __obj_dump(obj):
 
def _obj_dump(obj):
 
    """
 
    Custom function for dumping objects to JSON
 

	
 
    :param obj:
 
    """
 
    DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S"
 
    DATE_FORMAT = "%Y-%m-%d"
 
    if isinstance(obj, complex):
 
        return [obj.real, obj.imag]
 
    elif isinstance(obj, datetime.datetime):
 
        return obj.strftime(DATETIME_FORMAT)
 
    elif isinstance(obj, datetime.date):
 
        return obj.strftime(DATE_FORMAT)
 
    elif isinstance(obj, set):
 
        return list(obj)
 
    elif isinstance(obj, OrderedDict):
 
        return obj.as_dict()
 
    elif hasattr(obj, '__json__'):
 
        if callable(obj.__json__):
 
            return obj.__json__()
 
        else:
 
            return obj.__json__
 
    else:
 
        raise NotImplementedError
 

	
 
try:
 
    import json
 

	
 
    # extended JSON encoder for json
 
    class ExtendedEncoder(json.JSONEncoder):
 
        def default(self, obj):
 
            try:
 
                return __obj_dump(obj)
 
                return _obj_dump(obj)
 
            except NotImplementedError:
 
                pass
 
            return json.JSONEncoder.default(self, obj)
 
    # monkey-patch JSON encoder to use extended version
 
    json.dumps = functools.partial(json.dumps, cls=ExtendedEncoder)
 
except ImportError:
 
    import simplejson as json
 

	
 
    def extended_encode(obj):
 
        try:
 
            return __obj_dump(obj)
 
            return _obj_dump(obj)
 
        except NotImplementedError:
 
            pass
 
        raise TypeError("%r is not JSON serializable" % (obj,))
 
    json.dumps = functools.partial(json.dumps, default=extended_encode)
 

	
 

	
rhodecode/model/db.py
Show inline comments
 
@@ -378,12 +378,15 @@ class User(Base, BaseModel):
 
        self.last_login = datetime.datetime.now()
 
        Session.add(self)
 
        log.debug('updated user %s lastlogin' % self.username)
 

	
 
    def __json__(self):
 
        return dict(
 
            user_id=self.user_id,
 
            first_name=self.name,
 
            last_name=self.lastname,
 
            email=self.email,
 
            full_name=self.full_name,
 
            full_name_or_username=self.full_name_or_username,
 
            short_contact=self.short_contact,
 
            full_contact=self.full_contact
 
        )
0 comments (0 inline, 0 general)