« Return to Thread: SqlAlchemy Adapter

Re: SqlAlchemy Adapter

by Nikos Papagrigoriou :: Rate this Message:

Reply to Author | View in Thread

I lately found that in order to get the mapper it is better to call:

mapper = sqlalchemy.orm.util.object_mapper(obj, False)

and check if mapper is None.

The documentation says:
def object_mapper(object, raiseerror=True):
     """Given an object, return the primary Mapper associated with the  
object instance.

         object
             The object instance.

         raiseerror
             Defaults to True: raise an ``InvalidRequestError`` if no  
mapper can
             be located.  If False, return None.

     """

On Sep 22, 2008, at 12:24 AM, dthompso@... wrote:

> Thanks for the suggestion. I used your code, but I ran into problems  
> with custom
> collections (classes that are decorated with  
> @sqlalchemy.collection.iterator,
> etc.) because they don't have a class manager. I added a simple  
> check that uses

Could you please post an example?

>
> the mapper if the object has a class manager, or the __dict__ if it  
> doesn't.
> Seems to work with my setup (SA 0.5).
>
> Thanks
> -Dave
>
>
> Quoting nikos@...:
>
>> Hi Dave,
>>
>> I had to make slight changes to your version of SQLAlchemy adapter to
>> return the correct results for my project. The patch is:
>>
>> ----------->8------------- _sqlalchemy.patch --------------
>> >8---------------
>> --- /home/papagr/_sqlalchemy_old.py  2008-09-18 17:29:06.000000000  
>> +0200
>> +++ /home/papagr/_sqlalchemy_new.py  2008-09-18 17:29:20.000000000  
>> +0200
>> @@ -17,14 +17,15 @@
>>          return pyamf.util.native_get_attrs(obj)
>>
>>      attrs = {}
>> -    for property in obj.__dict__:
>> -        if property in sa_properties:
>> +    mapper = obj._sa_class_manager.mapper
>> +    for property in mapper.iterate_properties:
>> +        if property.key in sa_properties:
>>              continue
>>
>> -        if property.startswith('__'):
>> +        if property.key.startswith('__'):
>>              continue
>>
>> -        attrs[property] = getattr(obj, property)
>> +        attrs[property.key] = getattr(obj, property.key)
>>      return attrs
>>
>>  def write_SA_collection(obj):
>> ----------->8------------- _sqlalchemy.patch --------------
>> >8---------------
>>
>> The reason for using object's mapper to iterate properties instead of
>> fetching object's __dict__ is because SQLAlchemy initially creates
>> _CompileOnAttr except if you manually call mapper's compile method.
>>
>> Expecting your comments,
>>
>> Cheers,
>>
>> Nikos.
>
>
>

_______________________________________________
PyAMF dev mailing list - dev@...
http://lists.pyamf.org/mailman/listinfo/dev

 « Return to Thread: SqlAlchemy Adapter