Json serialization of sqlalchemy proxies

I am serializing converted SQLAlchemy objects with json.dumps. And I would like my proxy association property objects to also serialize correctly. By default, they are not serialized correctly, so I had to write a specific JSON encoder:

from sqlalchemy.ext.associationproxy import _AssociationList
class MyEncoder(JSONEncoder):
    def default(self, obj):
        if isinstance(obj, _AssociationList):
            return list(obj)
        return JSONEncoder.default(self, obj)

This does not look good, because I need to import _AssociationList, which is closed to SQLAlchemy.

Any other option?

+3
source share
1 answer

, _AssociationList, : ""? ! (duck typing, . Python: , ( )).

def is_sequence(arg):
    return (not hasattr(arg, "strip") and
        hasattr(arg, "__getitem__") or
        hasattr(arg, "__iter__"))

class MyEncoder(JSONEncoder):
    def default(self, obj):
        if is_sequence(obj):
            return list(obj)
        return JSONEncoder.default(self, obj)

, , _AssociationLists ! , int ..

0

All Articles