SQLAlchemy和Pylons的错误“无法在映射器上找到配置的绑定”

3 投票
1 回答
6208 浏览
提问于 2025-04-15 18:54

我不太明白我哪里做错了,才会出现这个提示。希望能得到一些关于我配置的帮助。

"""The application's model objects"""
import sqlalchemy as sa
from sqlalchemy import orm

from project.model import meta

def now():
    return datetime.datetime.now()

def init_model(engine):
    """Call me before using any of the tables or classes in the model"""
    sm = orm.sessionmaker(autoflush=True, autocommit=True, bind=engine)
    meta.Session.configure(bind=engine)
    meta.engine = engine
    meta.Session = orm.scoped_session(sm)

class User(object):
    pass

t_user = sa.Table("User", meta.metadata,
sa.Column("id", sa.types.Integer, primary_key=True),
sa.Column("name", sa.types.String(100), nullable=False),
sa.Column("first_name", sa.types.String(100), nullable=False),
sa.Column("last_name", sa.types.String(100), nullable=False),
sa.Column("email", sa.types.String(100), nullable=False),
sa.Column("password", sa.types.String(32), nullable=False)
)

orm.mapper(User,t_user)

我在Python控制台里执行了:

from project.model import *

mr_jones = User()
meta.Session.add(mr_jones)
mr_jones.name = 'JR Jones'
meta.Session.commit()

然后我收到的错误是:

sqlalchemy.exc.UnboundExecutionError: Could not locate a bind configured on mapper Mapper|User|User or this Session

谢谢你的帮助。

1 个回答

3

这个问题已经解决了。我之前不知道在命令行使用pylons的时候,必须要包含整个环境:

from paste.deploy import appconfig
from pylons import config

from project.config.environment import load_environment

conf = appconfig('config:development.ini', relative_to='.')
load_environment(conf.global_conf, conf.local_conf)

from project.model import *

这样之后,数据库查询就能顺利执行了。

撰写回答