无法使用经典映射找到在映射器上配置的绑定

时间:2012-05-27 00:42:26

标签: python sqlalchemy python-2.7 bottle

我正在尝试从mysql加载User对象,但我一直收到UnboundExecutionError:无法找到在mapper Mapper | UserDo | user,SQL表达式或此Session上配置的绑定。我正在使用经典映射。

Base = declarative_base()

# A default constructor is created if one is not already present,
# which accepts keyword arguments of the same name as that of the mapped attributes.

class UserDo(Base):
    __tablename__ = 'user'

    id = Column(Integer, primary_key = True)
    fname = Column(String(100))
    lname = Column(String(100))
    email = Column(String(200))
    salt = Column(String(100))
    created_on = Column(TIMESTAMP) # from sqlalchemy.dialects.mysql import TIMESTAMP

class BaseService(object):

    def __init__(self):
        self._engine = create_engine('mysql://root@localhost/my_db', pool_recycle = 3600)
        self._Session = sessionmaker(bind = self._engine)
        self._session = Session()

class UserService(BaseService):

    def create(self, data):
        print self._session.query(UserDo).first() # Error

我想知道我是否因为create_engine语句而收到错误。也许我没有提供正确的连接格式。我的本地数据库没有密码。

另外,我注意到的其他事情:     print self._session.query(UserDo)

打印SELECT“user”.id AS user_id,“user”.fname AS user_fname,“user”.lname AS user_lname,“user”.email AS user_email,“user”.salt AS user_salt,“user”.created_on AS user_created_on 来自“用户”

这在语法上是不正确的。无论哪种方式,我都不关心SQLAlchemy在内部做什么,只要做User.fname,User.lname(等),按照定义工作。

任何人都能看到发生了什么?

1 个答案:

答案 0 :(得分:5)

出于某种原因,当我这样做时,SQLAlchemy 0.8不喜欢它(创建实例变量):

class BaseService(object):

    def __init__(self):
        self._engine = create_engine('mysql://root@localhost/my_db', pool_recycle = 3600)
        self._Session = sessionmaker(bind = self._engine)
        self._session = Session()

修复方法是让它们变为静态:

class BaseService(object):
    engine = create_engine('mysql://root@localhost/my_db', pool_recycle = 3600)
    Session = sessionmaker(bind = engine)
    session = Session()

然后你可以这样做:

class UserService(BaseService):

    def create(self, data):
        BaseService.session.query(UserDo).first()