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)
 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.º 3
0
    def to_date(self, data, correction=True):
        import datetime_safe
        from dateutil.parser import parse
        try:
            if data.count('/') == 2 or data.count(':') == 2 or data.count(' ') >= 2:
                date = parse(data, dayfirst=True)
                if correction:
                    date = date - relativedelta(years=4, days=1)
                date = datetime_safe.new_datetime(date)
                return date
        except:
            pass

        return data
Ejemplo n.º 4
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
Ejemplo n.º 5
0
    def default_impl(obj):
        # Load objects from the datastore (could be done in parallel)
        if strategy:
            for stat in strategy:
                if hasattr(stat, 'restler_collection_types'):
                    if stat.restler_collection_types(obj):
                        return [o for o in obj]

                if hasattr(stat, 'restler_encoder'):
                        encoded_obj = stat.restler_encoder(obj)
                        if encoded_obj is not None:
                            return encoded_obj

        if isinstance(obj, datetime.datetime):
            d = datetime_safe.new_datetime(obj)
            return d.strftime("%s %s" % (DATE_FORMAT, TIME_FORMAT))
        if isinstance(obj, datetime.date):
            d = datetime_safe.new_date(obj)
            return d.strftime(DATE_FORMAT)
        if isinstance(obj, datetime.time):
            return obj.strftime(TIME_FORMAT)
        if isinstance(obj, decimal.Decimal):
            return str(obj)

        ret = {}  # What we're most likely going to return (populated, of course)
        if hasattr(obj, 'restler_kind') or isinstance(obj, models.TransientModel):
            model = {}
            kind = obj.restler_kind(obj)
            # User the model's properties
            if strategy is None:
                fields = obj.restler_properties(obj)
            else:
                # Load the customized mappings
                fields = strategy.get(obj.__class__, None)
                if fields is None:
                    fields = obj.restler_properties(obj)
                # 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
Ejemplo n.º 6
0
    def handleCharData(self, data):
        if data in ('\n'):
            pass
        elif data in ('9/5/2002', '28/11/2002'):
            pass
        if self.in_cell_value:
            self.collected_string += data
            self.data = self.collected_string

            if self.colType == "s":  # shared string
                self.data = self.sharedStrings[int(self.data)]
                _date = self.to_date(self.data, False)
                if _date is not self.data:
                    self.data = _date.strftime(str(self.dateformat))
            elif self.colType == "b":  # boolean
                self.data = (int(data) == 1 and "TRUE") or (int(data) == 0 and "FALSE") or data
            elif self.s_attr:
                s = int(self.s_attr)

                # get cell format
                format_str = None
                xfs_numfmt = self.styles.cellXfs[s]
                if xfs_numfmt in self.styles.numFmts:
                    format_str = self.styles.numFmts[xfs_numfmt]
                elif xfs_numfmt in STANDARD_FORMATS:
                    format_str = STANDARD_FORMATS[xfs_numfmt]
                # get format type
                if not format_str:
                    print("unknown format %s at %d" % (format_str, xfs_numfmt))
                    return
                format_type = None
                if format_str in FORMATS:
                    format_type = FORMATS[format_str]
                elif re.match("^\d+(\.\d+)?$", self.data) and re.match(".*[hsmdyY]", format_str) and not re.match('.*\[.*[dmhys].*\]', format_str):
                    # it must be date format
                    if float(self.data) < 1:
                        format_type = "time"
                    else:
                        format_type = "date"
                elif re.match("^-?\d+(.\d+)?$", self.data):
                    format_type = "float"
                if format_type:
                    try:
                        if format_type == 'date':  # date/time
                            try:
                                if self.workbook.date1904:
                                    date = datetime.datetime(1904, 1, 1) + datetime.timedelta(float(self.data))
                                    date = date - relativedelta(years=4, days=1)
                                else:
                                    date = datetime.datetime(1899, 12, 30) + datetime.timedelta(float(self.data))
                            except:
                                date = self.to_date(self.data)

                            if self.dateformat:
                                # str(dateformat) - python2.5 bug, see: http://bugs.python.org/issue2782
                                date = datetime_safe.new_datetime(date)
                                self.data = date.strftime(str(self.dateformat))
                            else:
                                # ignore ";@", don't know what does it mean right now
                                dateformat = format_str.replace(";@", ""). \
                                    replace("yyyy", "%Y").replace("yy", "%y"). \
                                    replace("hh:mm", "%H:%M").replace("h", "%I").replace("%H%H", "%H").replace("ss", "%S"). \
                                    replace("dd", "d").replace("d", "%d"). \
                                    replace("am/pm", "%p"). \
                                    replace("mmmm", "%B").replace("mmm", "%b").replace(":mm", ":%M").replace("m", "%m").replace("%m%m", "%m")
                                self.data = date.strftime(str(dateformat)).strip()
                        elif format_type == 'time':  # time
                            t = int(round((float(self.data) % 1) * 24 * 60 * 60, 6)) / 60  # round to microseconds
                            self.data = "%.2i:%.2i" % (t / 60, t % 60)  # str(t / 60) + ":" + ('0' + str(t % 60))[-2:]
                        elif format_type == 'float' and ('E' in self.data or 'e' in self.data):
                            self.data = ("%f" % (float(self.data))).rstrip('0').rstrip('.')
                        elif format_type == 'float' and format_str[0:3] == '0.0':
                            self.data = ("%." + str(len(format_str.split(".")[1]) + (1 if ('%' in format_str) else 0)) + "f") % float(self.data)
                    except Exception as e:
                        print self.data, e
                        import logging
                        print logging.traceback.format_exc()
                        raise e

        if type(self.data) == str:
            self.data = self.data.replace(self.options['delimiter'], ' ')
            self.data = self.data.rstrip(' 00:00:00')