"""Custom JSON encoder to use in flaskify function. This encoder is used by default for json serialization happening in flask.flaskify helper function. It's purposes is to support the serialization of data types that are not supported by json serialization out of the box. The main goal is to support date and time types. Currently the encoder supports python datetime and date (including subclasses) and neotime.DateTime. By default dates and times are formatted using iso-8601 format using naive approach. It's assumed that we are working with UTC date, since Z token is hard-coded in date format string, and timezone info is not being respected. If you need to handle timezone information you can subclass the existing encoder and provide a custom date format and (or) logic. """ from datetime import date from datetime import datetime from json import JSONEncoder NEO4J_DATE_CLASS = 'DateTime' class FlaskEncoder(JSONEncoder): """Custom JSON encoder to use in flaskify function.""" DEFAULT_DATE_FORMAT = '%Y-%m-%dT%H:%M:%S.%fZ' def default(self, obj): """Convert date object to string for serialization. Args: obj: an instance of datetime.date, datetime.datetime, neotime.DateTime Returns: a string representing of date object. Example: 2020-06-25T15:23:23.213001Z """ # Note: we use type.__name__ here because otherwise we will have # to import neotime.DateTime which is not a good idea for a generic # library like owsresponse. date_type = type(obj).__name__ if isinstance(obj, (date, datetime)): return obj.strftime(self.DEFAULT_DATE_FORMAT) elif date_type == NEO4J_DATE_CLASS: return obj.to_native().strftime(self.DEFAULT_DATE_FORMAT) return JSONEncoder.default(self, obj)