I'm generating dynamic class in python. And I need to use it to create the object. I'm able to create the object successfully and use it. But when I try to unpickle the returned JSON string, I get <typ 'dict'> instead of the original object.
I've tried both the ways, i.e. either generate a class or create a dynamic module and create a class in the generated moduel. You can see both the codes in below snippet.
Please see the following code -
# to generate a pojo equivalent python class
def _create_pojo(self, pojo_class_name, param_schema):
#extracting the properties from the parameter 'schema'
pojo_properties = param_schema['properties']
#creating a list of property keys
pojo_property_list = []
for key in pojo_properties:
pojo_property_list.append(key)
source = \
"class %s(object):\n" % ( pojo_class_name )
source += " def __init__(self, %s" % ', '.join(pojo_property_list) +"):\n" #defining __init__ for the class
for prop in pojo_property_list: #creating a variable in the __init__ method for each property in the property list
source += " self.%s = %s\n" % (prop, prop)
'''m = self.importCode(source, 'test')
print(m)
obj = m.HelloWorldAgent_1_0_HelloWorldTopLevelType_com_tibco_tea_agent_Person('1', '1', '1')
print(obj)
x = jsonpickle.encode(obj)
print(x)
y = jsonpickle.decode(x)
print(y)'''
#generating the class code
class_code = compile( source, "<generated class>", "exec" )
fakeglobals = {}
eval( class_code, {"object" : object}, fakeglobals )
result = fakeglobals[ pojo_class_name ]
result ._source = source
#adding an entry to the _object_types dictionary to avoid the creation of pojo again
self._object_types[ pojo_class_name ] = result
return result
The code to call this function is as follows -
if some condition:
object_name = ast.literal_eval(jsonpickle.encode(val)).pop('py/object') - extracted the object_name
val = jsonpickle.encode(val, unpicklable=False)
And after getting the json string back, I prepare the json string to be decoded as follows -
result['py/object'] = object_name
result = str(result).replace("'", '"')
result = jsonpickle.decode(result)
I'm accessing them from interactive console as follows -
>>> import <my_module>
>>> t = <my_module>.<some_function>()
This is the pprint for the generated class -
'class '
'HelloWorldAgent_1_0_HelloWorldTopLevelType_com_tibco_tea_agent_Person(object):\n'
' def __init__(self, id, i, name):\n'
' self.id = id\n'
' self.i = i\n'
' self.name = name\n'
Now I'm instantiating the generated class.
>>> p = t._object_types['HelloWorldAgent_1_0_HelloWorldTopLevelType_com_tibco_tea_agent_Person']('1', '1', '1')
I'm accessing an operation which has the parameter and return type as the above generated class.
>>> t.products['HelloWorldTopLevelType'].hw8(p)
This is the result after decode, i.e. this is a dictionary, not an object -
{'id': '1', 'i': 1, 'py/object': '__builtin__.HelloWorldAgent_1_0_HelloWorldTopLevelType_com_tibco_tea_agent_Person', 'name': '1'}