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

2024-04-26 00:50:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试图从mysql加载用户对象,但我一直在获取UnboundExecutionError:找不到在映射器映射器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语句导致了错误。也许我没有提供正确的连接格式。我没有本地数据库的密码。

还有,我注意到的其他一些事情: 打印自我会话。查询(UserDo)

打印选择“用户”。id作为用户id,“用户”。fname作为用户fname,“用户”。lname作为用户名,“用户”。email作为用户email,“用户”。salt作为用户salt,“用户”。created作为用户创建 从“用户”

这在句法上是错误的。不管怎样,只要User.fname、User.lname(等等)按定义工作,我都不在乎SQLAlchemy在内部做什么。

有人看到了吗?


Tags: 用户selfidstringemailmysqlcolumnfname
1条回答
网友
1楼 · 发布于 2024-04-26 00:50:18

出于某种原因,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()

相关问题 更多 >