4

我正在尝试从 mysql 加载用户对象,但我不断收到 UnboundExecutionError:无法找到在映射器 Mapper|UserDo|user、SQL 表达式或此会话上配置的绑定。我正在使用经典映射。

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 FROM “用户”

这是一个语法错误。无论哪种方式,我都不关心 SQLAlchemy 在内部做什么,只要按照定义执行 User.fname、User.lname (等)。

有人看到发生了什么吗?

4

1 回答 1

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()
于 2012-05-27T03:49:46.647 回答