11import time
22from datetime import datetime , timedelta
33
4+ from linode_api4 .objects .serializable import JSONObject
5+
46from .filtering import FilterableMetaclass
57
68DATE_FORMAT = "%Y-%m-%dT%H:%M:%S"
@@ -30,6 +32,7 @@ def __init__(
3032 id_relationship = False ,
3133 slug_relationship = False ,
3234 nullable = False ,
35+ json_object = None ,
3336 ):
3437 """
3538 A Property is an attribute returned from the API, and defines metadata
@@ -56,6 +59,8 @@ def __init__(
5659 self .is_datetime = is_datetime
5760 self .id_relationship = id_relationship
5861 self .slug_relationship = slug_relationship
62+ self .nullable = nullable
63+ self .json_class = json_object
5964
6065
6166class MappedObject :
@@ -111,7 +116,7 @@ class Base(object, metaclass=FilterableMetaclass):
111116
112117 properties = {}
113118
114- def __init__ (self , client , id , json = {}):
119+ def __init__ (self , client : object , id : object , json : object = {}) -> object :
115120 self ._set ("_populated" , False )
116121 self ._set ("_last_updated" , datetime .min )
117122 self ._set ("_client" , client )
@@ -123,8 +128,8 @@ def __init__(self, client, id, json={}):
123128 #: be updated on access.
124129 self ._set ("_raw_json" , None )
125130
126- for prop in type (self ).properties :
127- self ._set (prop , None )
131+ for k in type (self ).properties :
132+ self ._set (k , None )
128133
129134 self ._set ("id" , id )
130135 if hasattr (type (self ), "id_attribute" ):
@@ -289,7 +294,7 @@ def _serialize(self):
289294
290295 value = getattr (self , k )
291296
292- if not value :
297+ if not v . nullable and ( value is None or value == "" ) :
293298 continue
294299
295300 # Let's allow explicit null values as both classes and instances
@@ -305,7 +310,7 @@ def _serialize(self):
305310 for k , v in result .items ():
306311 if isinstance (v , Base ):
307312 result [k ] = v .id
308- elif isinstance (v , MappedObject ):
313+ elif isinstance (v , MappedObject ) or issubclass ( type ( v ), JSONObject ) :
309314 result [k ] = v .dict
310315
311316 return result
@@ -376,6 +381,18 @@ def _populate(self, json):
376381 .properties [key ]
377382 .slug_relationship (self ._client , json [key ]),
378383 )
384+ elif type (self ).properties [key ].json_class :
385+ json_class = type (self ).properties [key ].json_class
386+ json_value = json [key ]
387+
388+ # build JSON object
389+ if isinstance (json_value , list ):
390+ # We need special handling for list responses
391+ value = [json_class .from_json (v ) for v in json_value ]
392+ else :
393+ value = json_class .from_json (json_value )
394+
395+ self ._set (key , value )
379396 elif type (json [key ]) is dict :
380397 self ._set (key , MappedObject (** json [key ]))
381398 elif type (json [key ]) is list :
0 commit comments