【问题标题】:Could not locate a bind configured on mapper using classical mapping找不到使用经典映射在映射器上配置的绑定
【发布时间】:2012-05-30 13:20:22
【问题描述】:

我正在尝试从 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 语句而收到错误。也许我没有为连接提供正确的格式。我没有本地数据库的密码。

另外,我注意到的其他一些事情: 打印 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(等),按定义工作。

有人知道发生了什么吗?

【问题讨论】:

    标签: python sqlalchemy python-2.7 bottle


    【解决方案1】:

    由于某种原因,当我这样做(创建实例变量)时,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()
    

    【讨论】:

    • 虽然这解决了手头的问题,但我想知道是否有人知道它为什么有效?
    • 我只是被这个咬了。我最好的理论是,在给定范围内预先存在的会话是不好的,因此将其放入函数范围会有所帮助。
    猜你喜欢
    • 2018-08-05
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-05-03
    • 2020-02-16
    • 2021-11-06
    • 2019-08-10
    • 2013-09-19
    相关资源
    最近更新 更多