@michael: changed to after_commit

@ivan:
Sorry for the late reply.  Here's a decent example.  I have this
working in production error free, but it's hardly done.  Note, the
code below is a specific example.  Let me know if you have questions

from sqlalchemy import orm

def get_session_id(session):
    session()  # Prime session.  Fails without doing this
    sessions = dict((v, k) for k, v in orm.session._sessions.items())
    return sessions[session]

# I put these in a class inherited by all my models.  There's probably
a better way

@property
def _loaded_relations(self):
    relations = set(name for name, obj in
self.__mapper__._props.iteritems()
                    if type(obj) is orm.properties.RelationProperty)
    return relations.difference(self._sa_instance_state.unloaded)

def cache(self):
    # Do not cached anything with deferred fields.  That could hurt
performance and cause more db hits, not to mention I find some edge
cases where it causes errors
    # Do not cached anything with loaded relations.  I'm trying to fix
this.  If you serialize them together, make sure to deserialize them
properly
    if not self._sa_instance_state.load_options and not
self._loaded_relations:
        memcache_client = get_memcache_client()
        try:
            serialized_instance = pickle.dumps(self)
        except pickle.PickleError:  # The object may include non-
serializable attributes
            pass
        else:
            memcache_client.set(self._cache_key, serialized_instance)

@classmethod
def find_by_id(cls, id, session=SESSION):  # I actually abstract this
a bit for different primary keys and unique fields, but it's a good
example
    key = cls.get_cache_key(id)
    memcache_client = get_memcache_client()
    serialized_instance = memcache_client.get(key)
    if serialized_instance is not None:
        cls()  # Prime model.  Fails without doing this
        instance = pickle.loads(serialized_instance)
        instance._sa_instance_state.session_id = get_session_id
(session)  # Attach to session
    else:
        instance = session.query(cls).filter_by(id=id).one()
        instance.cache()  # Serialize and store in memcache
    return instance

--

You received this message because you are subscribed to the Google Groups 
"sqlalchemy" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/sqlalchemy?hl=en.


Reply via email to