python - converting a subclass with __slots__ to json -


i total noob in python , couldn't myself did again , dreamed of couldn't achieve.

i wanted have class, can instantiated such:

my_class = myclass(**params) 

and consumed such, in flask:

jsonify(my_class) 

the expected outcome json:

{ "key" : "value", ... } 

now, implementation of myclass is,

class myclas(namedmutablesequence, document):     __slots__ = (         'key_1',         'key_2',         'key_3'     )  def __init__(self, **params):     namedmutablesequence.__init__(self, **params)     document.__init__(self, 'myclass')  def save(self):     self._db_col.update({'key_1': self.key_1}, {'key_2': self.key_2, 'key_3': self.key_3}) 

by now, wondering namedmutablesequence , document are...

    class namedmutablesequence(sequence):         ___slots__ = ()          def __init__(self, *positional_values, **keyword_values):             subclass_propeties = self.__slots__             key in subclass_propeties:                 setattr(self, key, keyword_values.get(key))              if positional_values:                 key, value in zip(subclass_propeties, positional_values):                     setattr(self, key, value)          def __str__(self):             values = ', '.join('%s=%r' % (key, getattr(self, key)) key in self.__slots__)             return '%s(%s)' % (clsname, values)          __repr__ = __str__          def __getitem__(self, item):             return getattr(self, item)          def __setitem__(self, item, value):             return setattr(self, item, value)          def __len__(self):             return len(self.__slots__) 

admittedly, copied someone's solution mutable namedtuple base class , fixed __getitem__ & __setitem__ allow my_class.key_1 = 'some value'

class document():     __slots__ = ('_db_col')      def __init__(self, collection):         self._db_col = mongo_db[collection] 

this spew out in attempt base class using throughout model classes db connection.

this is, in opinion, starts got on myself , created mess. because no matter try, can't stop raising typeerror: {string value of my_class} not json serializable.

to make matters worse, when try dict(my_class), shiny attributes must string error raised on getattr().

i still keep base classes , still need make json serializable.

how can save myself?

i found answer finally, , solution found stackoverflow post (how can convert python class slots dictionary?)

what did add method on namedmutablesequence such:

def json(self):     return {key : getattr(self, key, none) key in self.__slots__} 

and call when need json parsable dictionary, such:

my_class = myclass(**params) jsonify(my_class.json()) 

Comments

Popular posts from this blog

angular - DownloadURL return null in below code -

meteor - inserting data to database gives error "insert failed: Method '/texts/insert' not found" -