分离的SQLalchemy会话不能延迟加载backref对象

时间:2013-03-03 17:28:34

标签: python memcached sqlalchemy flask-sqlalchemy

我正在尝试在sqlalchemy和我的postgres DB之间添加一个pylibmc memcached层。 This post谈到了如何做到这一点。但我也想要backrefs(在关系中从一个到多个),所以我修改了帖子的user_classes.py来测试它。

我使UserStatus继承自database.MemcachedORMObject,并在UserTable.mapper中添加了一个backref。但是我得到一个“DetachedInstanceError:父实例未绑定到Sessi;在尝试访问backref时,属性'user'的延迟加载操作无法继续”。我正在使用Flask-SQLAlchemy == 0.16,SQLAlchemy == 0.8.0b2和pylibmc == 1.2.3。

class UserStatus(database.MemcachedORMObject):                                                      
    def __init__(self, name):                                                                      
        self.name = name                                                                            

UserStatusTable = Table('user_status', METADATA, \                                                  
    Column('user_status_id', Integer, primary_key=True),                                            
    Column('name', String)                                                                            )                                                                                                  
UserStatusTable.mapper = mapper(UserStatus, UserStatusTable)                                        
UserStatusTable.mapper.compile()                                                                    


class User(database.MemcachedORMObject):                                                            
    def __init__(self, name, email, password, user_status_id):                                      
        self.name = name                                                                            
        self.email = email                                                                          
        self.password = password                                                                    
        self.user_status_id = user_status_id                                                        

UserTable = Table('user', METADATA, \                                                              
    Column('user_id', Integer, primary_key=True),                                                  
    Column('name', String),
    Column('email', String),                                                                        
    Column('password', String),                                                                    
    Column('user_status_id', Integer),                                                              
    ForeignKeyConstraint(['user_status_id'], ['user_status.user_status_id'])                          )                                                                                                  
UserTable.mapper = mapper(User, UserTable,
  properties = { 'user_status': relation(UserStatus, backref='user', lazy=False)})                
UserTable.mapper.compile()

尝试访问backref时出错:

In [14]: from user_classes import *                                    In [15]: ust = UserStatus.fetch_by_field(UserStatus.user_status_id, 1) Memcached Getting: user_classes.UserStatus:(1)   In [16]: ust.user
--------------------------------------------------------------------------- DetachedInstanceError                     Traceback (most recent call last) <ipython-input-16-38fd625abed9> in <module>()
----> 1 ust.user /home/david/sqlalchemy-memcached/env/lib/python2.7/site-packages/sqlalchemy/orm/attribut es.pyc in __get__(self, instance, owner)
    249             return dict_[self.key]
    250         else:
--> 251             return self.impl.get(instance_state(instance), dict_)
    252
    253   /home/david/sqlalchemy-memcached/env/lib/python2.7/site-packages/sqlalchemy/orm/attribut es.pyc in get(self, state, dict_, passive)
    543                     value = callable_(passive)
    544                 elif self.callable_:
--> 545                     value = self.callable_(state, passive)
    546                 else:
    547                     value = ATTR_EMPTY   /home/david/sqlalchemy-memcached/env/lib/python2.7/site-packages/sqlalchemy/orm/strategi es.pyc in _load_for_state(self, state, passive)    495                 "Parent instance %s is not bound to a Session; "
    496                 "lazy load operation of attribute '%s' cannot proceed" %--> 497                 (orm_util.state_str(state), self.key)
    498             )
    499   DetachedInstanceError: Parent instance <UserStatus at 0x21e9dd0> is not bound to a Sessi on; lazy load operation of attribute 'user' cannot proceed

1 个答案:

答案 0 :(得分:1)

这是SQLAlchemy中的一个错误。我在错误跟踪器上报告了它:http://www.sqlalchemy.org/trac/ticket/2743

您始终可以遍历默认关系方向。因此,您的案例中的解决方法是更改​​关系的方向(这样您就可以从用户状态访问用户,但不能反过来)。

一般的解决方法(如果以后需要遍历两个方向)是修补定义backref的对象中的__dict__属性。对于bug跟踪器的测试用例,这将是:

for p in parents:
    for c in p.children:
        getattr(c, '__dict__')['parent'] = p
print parents[0].children[0].parent