Files
opensearch-pyd/elasticsearch/serializer.py
T

167 lines
4.5 KiB
Python
Raw Normal View History

# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you under
# the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
2020-04-23 11:22:08 -05:00
try:
import simplejson as json
except ImportError:
import json
2015-12-09 23:15:59 -08:00
import uuid
2013-05-02 23:42:11 +02:00
from datetime import date, datetime
2013-10-22 00:26:58 +02:00
from decimal import Decimal
2013-05-02 23:42:11 +02:00
2014-02-21 16:53:56 +01:00
from .compat import string_types
from .exceptions import ImproperlyConfigured, SerializationError
INTEGER_TYPES = ()
FLOAT_TYPES = (Decimal,)
TIME_TYPES = (date, datetime)
try:
import numpy as np
INTEGER_TYPES += (
np.int_,
np.intc,
np.int8,
np.int16,
np.int32,
np.int64,
np.uint8,
np.uint16,
np.uint32,
np.uint64,
)
FLOAT_TYPES += (
np.float_,
np.float16,
np.float32,
np.float64,
)
except ImportError:
np = None
try:
import pandas as pd
TIME_TYPES += (pd.Timestamp,)
except ImportError:
pd = None
2019-05-10 09:16:33 -06:00
class Serializer(object):
mimetype = ""
def loads(self, s):
raise NotImplementedError()
def dumps(self, data):
raise NotImplementedError()
class TextSerializer(Serializer):
2019-05-10 09:16:33 -06:00
mimetype = "text/plain"
def loads(self, s):
return s
def dumps(self, data):
2014-02-21 16:53:56 +01:00
if isinstance(data, string_types):
return data
2019-05-10 09:16:33 -06:00
raise SerializationError("Cannot serialize %r into text." % data)
2013-05-02 23:42:11 +02:00
class JSONSerializer(Serializer):
2019-05-10 09:16:33 -06:00
mimetype = "application/json"
2013-05-02 23:42:11 +02:00
def default(self, data):
2020-06-29 10:10:05 -05:00
if isinstance(data, TIME_TYPES) and getattr(pd, "NaT", None) is not data:
2013-05-02 23:42:11 +02:00
return data.isoformat()
2015-12-13 20:30:28 -08:00
elif isinstance(data, uuid.UUID):
2015-12-09 23:15:59 -08:00
return str(data)
elif isinstance(data, FLOAT_TYPES):
return float(data)
elif INTEGER_TYPES and isinstance(data, INTEGER_TYPES):
return int(data)
# Special cases for numpy and pandas types
elif np:
if isinstance(data, np.bool_):
return bool(data)
elif isinstance(data, np.datetime64):
return data.item().isoformat()
elif isinstance(data, np.ndarray):
return data.tolist()
if pd:
if isinstance(data, (pd.Series, pd.Categorical)):
return data.tolist()
2020-06-29 10:10:05 -05:00
elif data is getattr(pd, "NA", None):
return None
raise TypeError("Unable to serialize %r (type: %s)" % (data, type(data)))
2013-05-02 23:42:11 +02:00
def loads(self, s):
try:
return json.loads(s)
2013-05-03 17:56:27 +02:00
except (ValueError, TypeError) as e:
2013-07-30 15:05:46 +02:00
raise SerializationError(s, e)
2013-05-02 23:42:11 +02:00
def dumps(self, data):
2013-06-20 14:07:09 +02:00
# don't serialize strings
2014-02-21 16:53:56 +01:00
if isinstance(data, string_types):
2013-12-04 15:07:56 +01:00
return data
2013-06-20 14:07:09 +02:00
2013-05-02 23:42:11 +02:00
try:
return json.dumps(
2019-05-10 09:16:33 -06:00
data, default=self.default, ensure_ascii=False, separators=(",", ":")
)
2013-05-03 17:56:27 +02:00
except (ValueError, TypeError) as e:
2013-07-30 15:05:46 +02:00
raise SerializationError(data, e)
2013-05-02 23:42:11 +02:00
2019-05-10 09:16:33 -06:00
DEFAULT_SERIALIZERS = {
JSONSerializer.mimetype: JSONSerializer(),
TextSerializer.mimetype: TextSerializer(),
}
2019-05-10 09:16:33 -06:00
class Deserializer(object):
2019-05-10 09:16:33 -06:00
def __init__(self, serializers, default_mimetype="application/json"):
try:
self.default = serializers[default_mimetype]
except KeyError:
2019-05-10 09:16:33 -06:00
raise ImproperlyConfigured(
"Cannot find default serializer (%s)" % default_mimetype
)
self.serializers = serializers
def loads(self, s, mimetype=None):
if not mimetype:
deserializer = self.default
else:
# split out charset
2019-05-10 09:16:33 -06:00
mimetype, _, _ = mimetype.partition(";")
try:
deserializer = self.serializers[mimetype]
except KeyError:
2019-05-10 09:16:33 -06:00
raise SerializationError(
"Unknown mimetype, unable to deserialize: %s" % mimetype
)
return deserializer.loads(s)