创建SQL表时总是收到“元数据未绑定到引擎或连接”错误

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

这是我现在的代码:

def init_model(engine):

    global t_user
    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, nullable=False),                      
    autoload=True,                                                               
    autoload_with=engine                                                         
    )                                                                            

    orm.mapper(User, t_user)                                                     

    meta.Session.configure(bind=engine)                                          
    meta.Session = orm.scoped_session(sm)
    meta.engine = engine

然后我尝试执行:

>>> meta.metadata.create_all(bind=meta.engine)

结果收到这个错误:

raise exc.UnboundExecutionError(msg)
sqlalchemy.exc.UnboundExecutionError: The MetaData is not bound to an Engine or     Connection.  Execution can not proceed without a database to execute against.  Either execute with an explicit connection or assign the MetaData's .bind to enable implicit execution.

在我的development.ini文件里,我有:

# SQLAlchemy database URL
sqlalchemy.url = sqlite:///%(here)s/development.db

我刚接触Python的pylons,对如何解决这个问题一点头绪都没有。对有经验的人来说,这可能是个简单的修复。谢谢。

1 个回答

2

这个问题解决了。我之前不知道在命令行使用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 *

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

撰写回答