Просмотр исходного кода

Add a to_json method to (Base)CloudResource

Enis Afgan 10 лет назад
Родитель
Сommit
54897d5162
2 измененных файлов с 15 добавлено и 0 удалено
  1. 8 0
      cloudbridge/cloud/base/resources.py
  2. 7 0
      cloudbridge/cloud/interfaces/resources.py

+ 8 - 0
cloudbridge/cloud/base/resources.py

@@ -1,7 +1,9 @@
 """
 Base implementation for data objects exposed through a provider or service
 """
+import inspect
 import itertools
+import json
 import logging
 import time
 import six
@@ -47,6 +49,12 @@ class BaseCloudResource(CloudResource):
     def _provider(self):
         return self.__provider
 
+    def to_json(self):
+        # Get all attributes but filter methods and private/magic ones
+        attr = inspect.getmembers(self, lambda a: not(inspect.isroutine(a)))
+        js = {k: v for(k, v) in attr if not k.startswith('_')}
+        return json.dumps(js)
+
 
 class BaseObjectLifeCycleMixin(ObjectLifeCycleMixin):
     """

+ 7 - 0
cloudbridge/cloud/interfaces/resources.py

@@ -44,6 +44,13 @@ class CloudResource(object):
         """
         pass
 
+    @abstractmethod
+    def to_json(self):
+        """
+        Returns a JSON representation of the CloudResource object.
+        """
+        pass
+
 
 class CloudBridgeBaseException(Exception):