Exemplo n.º 1
0
 def default(self, o):
     # See "Date Time String Format" in the ECMA-262 specification.
     if isinstance(o, datetime.datetime):
         r = o.isoformat()
         if o.microsecond:
             r = r[:23] + r[26:]
         if r.endswith('+00:00'):
             r = r[:-6] + 'Z'
         return r
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         if is_aware(o):
             raise ValueError("JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
     elif isinstance(o, decimal.Decimal):
         return str(o)
     elif isinstance(o, uuid.UUID):
         return str(o)
     elif isinstance(o, Promise):
         return six.text_type(o)
     else:
         return super(DjangoJSONEncoder, self).default(o)
Exemplo n.º 2
0
 def test_microseconds(self):
     duration = datetime.timedelta(hours=1,
                                   minutes=3,
                                   seconds=5,
                                   microseconds=12345)
     self.assertEqual(parse_duration(duration_iso_string(duration)),
                      duration)
Exemplo n.º 3
0
 def default(self, o):
     # See "Date Time String Format" in the ECMA-262 specification.
     if isinstance(o, datetime.datetime):
         return timezone.localtime(o).strftime(DATE_TIME_FORMAT)
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         if is_aware(o):
             raise ValueError("JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
     elif isinstance(o, decimal.Decimal):
         return str(o)
     elif isinstance(o, uuid.UUID):
         return str(o)
     elif isinstance(o, Promise):
         return six.text_type(o)
     elif isinstance(o, CallableBool):
         return bool(o)
     elif isinstance(o, QuerySet):
         return list(o.values())
     else:
         return super(JSONEncoder, self).default(o)
Exemplo n.º 4
0
 def default(self, o):
     # See "Date Time String Format" in the ECMA-262 specification.
     if isinstance(o, datetime.datetime):
         return strftime_local(o, fmt="%Y-%m-%d %H:%M:%S%z")
     elif isinstance(o, datetime.date):
         return date_to_string(o)
     elif isinstance(o, datetime.time):
         if is_aware(o):
             raise ValueError("JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
     elif isinstance(o, uuid.UUID) or isinstance(o, decimal.Decimal):
         return str(o)
     elif isinstance(o, Promise):
         return six.text_type(o)
     elif isinstance(o, CallableBool):
         return bool(o)
     elif isinstance(o, set):
         return list(o)
     else:
         return super(DjangoJSONEncoderExtend, self).default(o)
Exemplo n.º 5
0
 def default(self, o):
     # See "Date Time String Format" in the ECMA-262 specification.
     if isinstance(o, datetime.datetime):
         r = o.isoformat()
         # keep micro second
         # if o.microsecond:
         #     r = r[:23] + r[26:]
         if r.endswith('+00:00'):
             r = r[:-6] + 'Z'
         return r
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         if is_aware(o):
             raise ValueError("JSON cannot represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
     elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
         return str(o)
     else:
         return super().default(o)
Exemplo n.º 6
0
 def default(self, o):
     # See "Date Time String Format" in the ECMA-262 specification.
     print('Build Type', type(o))
     
     if isinstance(o, datetime.datetime):
         return timezone.localtime(o).strftime(DATE_TIME_FORMAT)
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         if is_aware(o):
             raise ValueError("JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
     elif isinstance(o, decimal.Decimal):
         return str(o)
     elif isinstance(o, uuid.UUID):
         return str(o)
     elif isinstance(o, Promise):
         return six.text_type(o)
     elif isinstance(o, QuerySet):
         return list(o.values())
     elif isinstance(o, Client):
         return model_to_dict(o)
     else:
         return super(JSONEncoder, self).default(o)
Exemplo n.º 7
0
 def default(self, o):
     # See "Date Time String Format" in the ECMA-262 specification.
     if isinstance(o, datetime.datetime):
         r = o.isoformat()
         if o.microsecond:
             r = r[:23] + r[26:]
         if r.endswith('+00:00'):
             r = r[:-6] + 'Z'
         return r
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         if is_aware(o):
             raise ValueError("JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
     elif isinstance(o, decimal.Decimal):
         return str(o)
     elif isinstance(o, uuid.UUID):
         return str(o)
     elif isinstance(o, Promise):
         return six.text_type(o)
     elif isinstance(o, CallableBool):
         return bool(o)
     else:
         return super(DjangoJSONEncoder, self).default(o)
Exemplo n.º 8
0
def serialize_data(o):
    if isinstance(o, datetime.datetime):
        r = o.isoformat()
        if o.microsecond:
            r = r[:23] + r[26:]
        if r.endswith('+00:00'):
            r = r[:-6] + 'Z'
        return {'@type': 'datetime', '@value': r}
    elif isinstance(o, datetime.date):
        return {'@type': 'date', '@value': o.isoformat()}
    elif isinstance(o, datetime.time):
        if is_aware(o):
            raise ValueError("JSON can't represent timezone-aware times.")
        r = o.isoformat()
        if o.microsecond:
            r = r[:12]
        return {'@type': 'time', '@value': r}
    elif isinstance(o, datetime.timedelta):
        return {'@type': 'timedelta', '@value': duration_iso_string(o)}
    elif isinstance(o, decimal.Decimal):
        return {'@type': 'decimal', '@value': str(o)}
    elif isinstance(o, uuid.UUID):
        return {'@type': 'uuid', '@value': str(o)}
    elif isinstance(o, (list, tuple, set)):
        return [serialize_data(v) for v in o]
    elif isinstance(o, dict):
        return {k: serialize_data(v) for k, v in o.items()}
    else:
        return o
Exemplo n.º 9
0
 def default(self, o):
     # See "Date Time String Format" in the ECMA-262 specification.
     if isinstance(o, datetime.datetime):
         r = o.isoformat()
         if o.microsecond:
             r = r[:23] + r[26:]
         if r.endswith('+00:00'):
             r = r[:-6] + 'Z'
         return r
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         if is_aware(o):
             raise ValidationError(
                 "JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
     elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
         return str(o)
     elif isinstance(o, Model):
         return model_to_dict(o)
     elif isinstance(o, QuerySet):
         return models_to_dict(o)
     elif isinstance(o, Enum):
         return o.name
     else:
         return o.__dict__
Exemplo n.º 10
0
 def quote_value(self, value):
     if isinstance(value, (datetime.date, datetime.time, datetime.datetime)):
         return "'%s'" % value
     elif isinstance(value, datetime.timedelta):
         return "'%s'" % duration_iso_string(value)
     elif isinstance(value, str):
         return "'%s'" % value.replace("'", "''").replace("%", "%%")
     elif isinstance(value, (bytes, bytearray, memoryview)):
         return "'%s'" % value.hex()
     elif isinstance(value, bool):
         return "1" if value else "0"
     else:
         return str(value)
Exemplo n.º 11
0
 def default(self, o):
     # See "Date Time String Format" in the ECMA-262 specification.
     if isinstance(o, datetime.datetime):
         r = o.isoformat()
         if o.microsecond:
             r = r[:23] + r[26:]
         if r.endswith('+00:00'):
             r = r[:-6] + 'Z'
         return r
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         if is_aware(o):
             raise ValueError("JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
     elif isinstance(o, decimal.Decimal):
         return str(o)
     elif isinstance(o, uuid.UUID):
         return str(o)
     elif isinstance(o, Model):
         return model_to_dict(o)
     elif isinstance(o, QuerySet):
         json_serializer = get_serializer('json')()
         json_serializer.serialize(o)
         return json_serializer.getvalue()
     elif isinstance(o, ResultsPage):
         context = {
             'total': o.total,  # 总记录数
             'pagecount': o.pagecount,  # 总页数
             'pagelen': o.pagelen,  # 当前页总记录数
             'pagenum': o.pagenum,  # 当前页号
             'offset': o.offset,  # 当前页首 记录号
             'is_last_page': o.is_last_page(),  # 是否末页
             'has_exact_length'
             'results': [whoosh_hit_to_dict(i) for i in o],
         }
         return context
     elif isinstance(o, Promise):
         return six.text_type(o)
     else:
         return super(JSONEncoder, self).default(o)
Exemplo n.º 12
0
    def default(self, o):

        # See "Date Time String Format" in the ECMA-262 specification.
        if isinstance(o, datetime.datetime):
            return dttime_format(o)
        if isinstance(o, datetime.date):
            return o.isoformat()
        if isinstance(o, datetime.time):
            if timezone.is_aware(o):
                raise ValueError("JSON can't represent timezone-aware times.")
            result = o.isoformat()
            if o.microsecond:
                result = result[:12]
            return result
        if isinstance(o, datetime.timedelta):
            return duration_iso_string(o)
        if isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
            return str(o)
        return super().default(o)
Exemplo n.º 13
0
 def default(self, o):
     # See "Date Time String Format" in the ECMA-262 specification.
     if isinstance(o, datetime.datetime):
         r = o.isoformat()
         if o.microsecond:
             r = r[:23] + r[26:]
         if r.endswith('+00:00'):
             r = r[:-6] + 'Z'
         return r
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         if is_aware(o):
             raise ValueError("JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
Exemplo n.º 14
0
 def default(self, o):
     # See "Date Time String Format" in the ECMA-262 specification.
     # 不强制要求遵守ECMA-262关于日期格式的定义,可以在Settings中配置日期格式相关
     # 默认的日期格式配置在apizen/config.py
     if isinstance(o, datetime.datetime):
         r = o.strftime(CustomJSONEncoder.datetime_format)
         return r
     elif isinstance(o, datetime.date):
         r = o.strftime(CustomJSONEncoder.date_format)
         return r
     elif isinstance(o, datetime.time):
         if is_aware(o):
             raise ValueError("JSON can't represent timezone-aware times.")
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
     elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)):
         return str(o)
     else:
         return super().default(o)
Exemplo n.º 15
0
    def default(self, o):
        fields = {}

        for f in o._meta.fields:
            val = getattr(o, f.name)
            if isinstance(f, models.ForeignKey) or isinstance(
                    f, models.OneToOneField):
                fields[f.name] = {
                    "id": val.id if val else "",
                    "name": str(val) if val else ""
                }
            elif isinstance(f, models.FileField):
                fields[f.name] = val.name
            else:
                if isinstance(val, datetime.datetime):
                    fields[f.name] = to_datetime_format(val)
                elif isinstance(val, datetime.date):
                    fields[f.name] = to_date_format(val)
                elif isinstance(val, datetime.time):
                    if is_aware(val):
                        raise ValueError(
                            "JSON can't represent timezone-aware times.")
                    fields[f.name] = to_time_format(val)
                elif isinstance(val, datetime.timedelta):
                    fields[f.name] = duration_iso_string(val)
                elif isinstance(val, (decimal.Decimal, uuid.UUID, Promise)):
                    fields[f.name] = str(val)
                else:
                    fields[f.name] = str(val)

        for f in o._meta.many_to_many:
            fields[f.name] = []
            qs = getattr(o, f.name).all()
            for obj in qs:
                fields[f.name].append({"id": obj.id, "name": str(obj)})

        return fields
Exemplo n.º 16
0
 def default(self, o):
     if isinstance(o, datetime.datetime):
         r = o.isoformat()
         if o.microsecond:
             r = r[:23] + r[26:]
         if r.endswith('+00:00'):
             r = r[:-6] + 'Z'
         return r
     elif isinstance(o, datetime.date):
         return o.isoformat()
     elif isinstance(o, datetime.time):
         r = o.isoformat()
         if o.microsecond:
             r = r[:12]
         return r
     elif isinstance(o, datetime.timedelta):
         return duration_iso_string(o)
     elif isinstance(o, pytz.tzinfo.tzinfo):
         return str(o)
     elif isinstance(o, (uuid.UUID, Promise)):
         return str(o)
     elif isinstance(o, decimal.Decimal):
         return float(o)
     elif isinstance(o, dict):
         return o
     elif isinstance(o, Mapping):
         return dict(o)
     elif isinstance(o, Collection) and not isinstance(o, str):
         return list(o)
     elif type(o) is str or type(o) is int or type(o) is float or type(
             o) is bool:
         return o
     elif hasattr(o, '__dict__'):
         return {k: self.default(v) for k, v in o.__dict__.items()}
     else:
         return super().default(o)
Exemplo n.º 17
0
 def test_simple(self):
     duration = datetime.timedelta(hours=1, minutes=3, seconds=5)
     self.assertEqual(duration_iso_string(duration), 'P0DT01H03M05S')
Exemplo n.º 18
0
 def test_negative(self):
     duration = -1 * datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)
     self.assertEqual(duration_iso_string(duration), '-P1DT01H03M05S')
Exemplo n.º 19
0
 def test_microseconds(self):
     duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345)
     self.assertEqual(duration_iso_string(duration), 'P0DT01H03M05.012345S')
Exemplo n.º 20
0
 def test_days(self):
     duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)
     self.assertEqual(parse_duration(duration_iso_string(duration)), duration)
Exemplo n.º 21
0
 def test_negative(self):
     duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5)
     self.assertEqual(
         parse_duration(duration_iso_string(duration)).total_seconds(),
         duration.total_seconds())
Exemplo n.º 22
0
 def test_negative(self):
     duration = -1 * datetime.timedelta(
         days=1, hours=1, minutes=3, seconds=5)
     self.assertEqual(duration_iso_string(duration), '-P1DT01H03M05S')
Exemplo n.º 23
0
 def test_days(self):
     duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)
     self.assertEqual(parse_duration(duration_iso_string(duration)),
                      duration)
Exemplo n.º 24
0
 def test_microseconds(self):
     duration = datetime.timedelta(hours=1,
                                   minutes=3,
                                   seconds=5,
                                   microseconds=12345)
     self.assertEqual(duration_iso_string(duration), 'P0DT01H03M05.012345S')
Exemplo n.º 25
0
 def test_simple(self):
     duration = datetime.timedelta(hours=1, minutes=3, seconds=5)
     self.assertEqual(duration_iso_string(duration), 'P0DT01H03M05S')
Exemplo n.º 26
0
 def test_microseconds(self):
     duration = datetime.timedelta(hours=1, minutes=3, seconds=5, microseconds=12345)
     self.assertEqual(parse_duration(duration_iso_string(duration)), duration)
Exemplo n.º 27
0
 def test_negative(self):
     duration = datetime.timedelta(days=-1, hours=1, minutes=3, seconds=5)
     self.assertEqual(parse_duration(duration_iso_string(duration)).total_seconds(), duration.total_seconds())
Exemplo n.º 28
0
 def test_days(self):
     duration = datetime.timedelta(days=1, hours=1, minutes=3, seconds=5)
     self.assertEqual(duration_iso_string(duration), "P1DT01H03M05S")