utils.default_serialiser
Contains the utility function that handles conversion of Python objects to JSON-compatible types.
1""" 2Contains the utility function that handles conversion of Python objects to JSON-compatible types. 3""" 4 5from datetime import datetime 6from decimal import Decimal 7 8 9def default_serialiser(obj): 10 """ 11 This function is a custom serialiser function that converts datetime objects into a ISO 8601 string and Decimal objects into floats. 12 13 # Arguments: 14 obj: A datetime or Decimal object. 15 16 # Returns: 17 An ISO 8601 formatted string, if obj is type datetime. 18 A float, if obj is type Decimal. 19 20 # Raises: 21 TypeError: If the object type is not supported for serialisation. 22 """ 23 if isinstance(obj, datetime): 24 return obj.isoformat() 25 if isinstance(obj, Decimal): 26 return float(obj) 27 raise TypeError(f"Type {type(obj)} not serializable")
def
default_serialiser(obj):
10def default_serialiser(obj): 11 """ 12 This function is a custom serialiser function that converts datetime objects into a ISO 8601 string and Decimal objects into floats. 13 14 # Arguments: 15 obj: A datetime or Decimal object. 16 17 # Returns: 18 An ISO 8601 formatted string, if obj is type datetime. 19 A float, if obj is type Decimal. 20 21 # Raises: 22 TypeError: If the object type is not supported for serialisation. 23 """ 24 if isinstance(obj, datetime): 25 return obj.isoformat() 26 if isinstance(obj, Decimal): 27 return float(obj) 28 raise TypeError(f"Type {type(obj)} not serializable")
This function is a custom serialiser function that converts datetime objects into a ISO 8601 string and Decimal objects into floats.
Arguments:
obj: A datetime or Decimal object.
Returns:
An ISO 8601 formatted string, if obj is type datetime.
A float, if obj is type Decimal.
Raises:
TypeError: If the object type is not supported for serialisation.