Hi,
I've been playing with the SQLAlchemy adapter, but I found that it was lacking
in a couple of ways. I coded my own, and it passes the tests. Here's the code:
what do you think?
"""
SQLAlchemy adapter (experimental!)
By Dave Thompson
@since: 0.4.0
"""
import sqlalchemy
import pyamf
sa_properties = ('_state', '_sa_instance_state', '_sa_class_manager')
def get_SA_attrs(obj):
"""Get attributes to be encoded for a SA object."""
if not is_SA_object(obj):
return pyamf.util.native_get_attrs(obj)
attrs = {}
for property in obj.__dict__:
if property in sa_properties:
continue
if property.startswith('__'):
continue
attrs[property] = getattr(obj, property)
return attrs
def write_SA_collection(obj):
"""Convert a SQLAlchemy collection to a native type."""
if isinstance(obj, sqlalchemy.orm.collections.InstrumentedList):
new_obj = []
new_obj.extend(obj)
return new_obj
if isinstance(obj, sqlalchemy.orm.collections.InstrumentedDict):
new_obj = {}
new_obj.update(obj)
return new_obj
if isinstance(obj, sqlalchemy.orm.collections.InstrumentedSet):
new_obj = Set()
new_obj.union(obj)
return new_obj
raise "Not a known SQLAlchemy collection type."
def is_SA_object(obj):
"""Detect if this object is a SQLAlchemy instance."""
if is_SA_collection(obj):
return False
for property in sa_properties:
if hasattr(obj, property):
return True
return False
def is_SA_collection(obj):
"""Detect if this object is a SQLAlchemy collection."""
if isinstance(obj, sqlalchemy.orm.collections.InstrumentedList):
return True
if isinstance(obj, sqlalchemy.orm.collections.InstrumentedSet):
return True
if isinstance(obj, sqlalchemy.orm.collections.InstrumentedDict):
return True
return False
# Replace this method with the adapter's
pyamf.util.native_get_attrs = pyamf.util.get_attrs
pyamf.util.get_attrs = get_SA_attrs
# turn collections into native objects
pyamf.add_type(is_SA_collection, write_SA_collection)
_______________________________________________
PyAMF dev mailing list -
dev@...
http://lists.pyamf.org/mailman/listinfo/dev