来自ORM的SQLAlchemy实例化对象失败,AttributeError:mapp

2024-09-30 01:34:51 发布

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

我一直在试图得到一个相当大的项目,在后端使用SQLAlchemy。我有跨多个文件的表模型,在它自己的文件中有一个声明性的基,还有一个用于包装通用SQLAlchemy函数的helper文件,以及驱动程序文件。在

我正在上传数据,然后决定添加一个列。因为这只是测试数据,所以我认为最简单的方法就是删除所有的表并重新开始。。。然后,当我试图重新创建模式和表时,公共声明性基类突然有了空的元数据。我通过导入类声明文件来解决这个问题——很奇怪,因为我以前不需要这些导入文件——而且它能够成功地重新创建模式。在

但是现在当我再次尝试创建对象时,我得到一个错误:

AttributeError: mapper

现在我完全糊涂了!有人能解释一下这里发生了什么吗?在我放弃这个模式之前,它运行得很好,现在我不能让它工作了。在

以下是我设置的框架:

基准.py

^{pr2}$

models1.py

from base import Base
class Business(Base):
    __tablename__ = 'business'
    id = Column(Integer, primary_key=True)

模型2.py:

from base import Base
class Category(Base):
    __tablename__ = 'category'
    id = Column(Integer, primary_key=True)

助手.py:

from base import Base

# I didn't need these two imports the first time I made the schema
# I added them after I was just getting an empty schema from base.Base
# but have no idea why they're needed now?
import models1
import models2

def setupDB():
    engine = getDBEngine(echo=True) # also a wrapped func (omitted for space)
    #instantiate the schema
    try:
        Base.metadata.create_all(engine, checkfirst=True)
        logger.info("Successfully instantiated Database with model schema")
    except:
        logger.error("Failed to instantieate Database with model schema")
        traceback.print_exc()

def dropAllTables():
    engine = getDBEngine(echo=True)
    # drop the schema
    try:
        Base.metadata.reflect(engine, extend_existing=True)
        Base.metadata.drop_all(engine)
        logger.info("Successfully dropped all the database tables in the schema")
    except:
        logger.error("Failed to drop all tables")
        traceback.print_exc()

驱动程序.py:

import models1
import models2

# ^ some code to get to this point
categories []
categories.append(
                models2.Category(alias=category['alias'],
                                 title=category['title']) # error occurs here
                )

堆栈跟踪:(为了完整性)

File "./main.py", line 16, in <module>
yelp.updateDBFromYelpFeed(fname)
  File "/Users/thomaseffland/Development/projects/health/pyhealth/pyhealth/data/sources/yelp.py", line 188, in updateDBFromYelpFeed
    title=category['title'])
  File "<string>", line 2, in __init__
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 347, in _new_state_if_none
    state = self._state_constructor(instance, self)
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 747, in __get__
    obj.__dict__[self.__name__] = result = self.fget(obj)
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/instrumentation.py", line 177, in _state_constructor
    self.dispatch.first_init(self, self.class_)
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/event/attr.py", line 256, in __call__
    fn(*args, **kw)
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2825, in _event_on_first_init
    configure_mappers()
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 2721, in configure_mappers
    mapper._post_configure_properties()
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/mapper.py", line 1710, in _post_configure_properties
    prop.init()
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/interfaces.py", line 183, in init
    self.do_init()
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1616, in do_init
    self._process_dependent_arguments()
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/orm/relationships.py", line 1673, in     _process_dependent_arguments
    self.target = self.mapper.mapped_table
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 833, in __getattr__
    return self._fallback_getattr(key)
  File "/Users/thomaseffland/.virtualenvs/health/lib/python2.7/site-packages/sqlalchemy/util/langhelpers.py", line 811, in _fallback_getattr
    raise AttributeError(key)
AttributeError: mapper

我知道这篇文章很长,但我想给出完整的图片。首先,我很困惑为什么base.Base模式是空的。现在我很困惑为什么Categories对象缺少一个映射器!在

如有任何帮助/见解/建议,我们将不胜感激,谢谢!在

编辑:

所以模型文件和helper.py在一个supackage中,driver.py实际上是同级子包中的一个文件,它的代码被包装在函数中。此驱动程序函数由包级主文件调用。所以我不认为这是因为SQLAlchemy还没有时间初始化?(如果我正确理解答案)以下是主文件的(相关部分):

主.py:

import models.helper as helper
helper.setupDB(echo=true) # SQLAlchemy echos the correct statements

import driverpackage.driver as driver
driver.updateDBFromFile(fname) # error occurs in here

而且驱动程序.py实际上看起来像:

import ..models.models1
import ..models.models2

def updateDBFromFile(fname):
    # ^ some code to get to this point
    categories []
    categories.append(
                    models2.Category(alias=category['alias'],
                                     title=category['title']) # error occurs here
                    )
    # a bunch more code

编辑2: 我开始怀疑潜在的问题与我突然需要导入所有模型来在helper.py中建立模式的原因是一样的。如果打印导入模型对象的表,则它们没有绑定的元数据或架构:

print YelpCategory.__dict__['__table__'].__dict__
####
{'schema': None, '_columns': <sqlalchemy.sql.base.ColumnCollection object at 0x102312ef0>, 
'name': 'yelp_category', 'description': 'yelp_category', 
'dispatch': <sqlalchemy.event.base.DDLEventsDispatch object at 0x10230caf0>, 
'indexes': set([]), 'foreign_keys': set([]), 
'columns': <sqlalchemy.sql.base.ImmutableColumnCollection object at 0x10230fc58>, 
'_prefixes': [], 
'_extra_dependencies': set([]), 
'fullname': 'yelp_category', 'metadata': MetaData(bind=None), 
'implicit_returning': True, 
'constraints': set([PrimaryKeyConstraint(Column('id', Integer(), table=<yelp_category>, primary_key=True, nullable=False))]), 'primary_key': PrimaryKeyConstraint(Column('id', Integer(), table=<yelp_category>, primary_key=True, nullable=False))}

我想知道为什么创建数据库的库中的元数据没有绑定?在


Tags: inpyimportselfsqlalchemylibpackagesline
2条回答

我猜发生错误是因为您在Python模块级别上执行代码。这段代码是在Python导入模块时执行的。在

  • 将代码移到函数。

  • 在SQLAlchemy正确初始化后调用函数。

  • 安装应用程序时,create_all()只需要调用一次,因为创建的表在数据库中持久化

  • 您需要DBSession.configure(bind=engine)或related,它将告诉模型它们与哪个数据库连接相关。这个问题不存在。

这个问题似乎已经不存在了,所以我将把我的研究结果张贴出来。很简单。我重构了代码来显式地提供类和经典的映射器,而不是使用声明性的基,一切都恢复正常了。。。在

相关问题 更多 >

    热门问题