def default(self, o):
     if isinstance(o, datetime.datetime):
         d = datetime_safe.new_datetime(o)
         return d.strftime("%s %s" % (self.DATE_FORMAT, self.TIME_FORMAT))
     elif isinstance(o, datetime.date):
         d = datetime_safe.new_date(o)
         return d.strftime(self.DATE_FORMAT)
     elif isinstance(o, datetime.time):
         return o.strftime(self.TIME_FORMAT)
     elif isinstance(o, decimal.Decimal):
         return str(o)
     else:
         return super(DjangoJSONEncoder, self).default(o)
Ejemplo n.º 2
0
    def default_impl(obj):
        # Load objects from the datastore (could be done in parallel)
        if isinstance(obj, db.Query):
            return [o for o in obj]
        if isinstance(obj, datetime.datetime):
            d = datetime_safe.new_datetime(obj)
            return d.strftime("%s %s" % (DATE_FORMAT, TIME_FORMAT))
        elif isinstance(obj, datetime.date):
            d = datetime_safe.new_date(obj)
            return d.strftime(DATE_FORMAT)
        elif isinstance(obj, datetime.time):
            return obj.strftime(TIME_FORMAT)
        if isinstance(obj, datetime.datetime):
            return obj.strftime("%s %s" % (DATE_FORMAT, TIME_FORMAT))
        elif isinstance(obj, datetime.date):
            return obj.strftime(DATE_FORMAT)
        elif isinstance(obj, datetime.time):
            return obj.strftime(TIME_FORMAT)
        elif isinstance(obj, decimal.Decimal):
            return str(obj)
        if isinstance(obj, db.GeoPt):
            return "%s %s" % (obj.lat, obj.lon)
        if isinstance(obj, db.IM):
            return "%s %s" % (obj.protocol, obj.address)
        if isinstance(obj, users.User):
            return obj.user_id() or obj.email()
        if isinstance(obj, blobstore.BlobInfo):
            return str(obj.key())  # TODO is this correct?
        ret = {
        }  # What we're most likely going to return (populated, of course)
        if isinstance(obj, (db.Model, models.TransientModel)):
            model = {}
            kind = obj.kind().lower()
            # User the model's properties
            if strategy is None:
                fields = obj.properties().keys()
            else:
                # Load the customized mappings
                fields = strategy.get(obj.__class__, None)
                if fields is None:
                    fields = obj.properties().keys()
                # If it's a dict, we're changing the output_name for the model
                elif isinstance(fields, dict):
                    if len(fields.keys()) != 1:
                        raise ValueError(
                            'fields must an instance dict(<model name>=<field list>)'
                        )
                    kind, fields = fields.items()[0]
                    # if kind is callable, we'll call it to get the output_name
                    if callable(kind):
                        kind = kind(obj)
            # Handle the case where we don't want the model name as part of the serialization
            if type_ == 'json' and bool(style['json']["flatten"]):
                model = ret
            else:
                ret[unicode(kind)] = model
            # catch the case where there's just one property (and it's not in a list/tuple)
            if not isinstance(fields, (tuple, list)):
                fields = [fields]
            target = None
            for field_name in fields:
                # Check to see if this remaps a field to a callable or a different field
                if isinstance(field_name, tuple):
                    field_name, target = field_name  # Only one key/value

                if callable(target):  # Defer to the callable
                    # if the function has exactly two arguments, assume we should include the context param
                    if hasattr(
                            target,
                            "func_code") and target.func_code.co_argcount == 2:
                        model[field_name] = target(obj, context)
                    else:  # No context passed
                        model[field_name] = target(obj)
                    # if we get back an instance of SKIP, don't include this field in the output
                    if isinstance(model[field_name], SkipField):
                        del model[field_name]
                else:
                    if target:  # Remapped name
                        if hasattr(obj, target):
                            model[field_name] = getattr(obj, target)
                        else:
                            raise ValueError("'%s' was not found " % target)
                    else:  # Common case (just the field)
                        model[field_name] = getattr(obj, field_name)
        return ret