2015-10-16 202 views
1

我一直在试图在后端使用SQLAlchemy来获得体面大小的项目。我有跨多个文件的表模型,它自己的文件中有一个声明基,还有一个帮助文件来包装常用的SQLAlchemy函数和驱动程序文件。SQLAlchemy从ORM实例化对象时出现AttributeError失败:mapper

我正在上传数据,然后决定添加一列。由于这只是测试数据,我认为最简单的方法是删除所有表并重新开始......然后,当我尝试重新创建模式和表时,常用的声明式基类突然有空元数据。我通过导入类声明文件解决了这个问题 - 奇怪,因为我之前不需要这些导入 - 并且能够成功重新创建模式。

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

AttributeError: mapper 

现在我完全糊涂了!有人可以解释这里发生了什么吗?在我放弃架构之前它工作正常,现在我无法正常工作。

这是我设置的骨架:

base.py

from sqlalchemy.ext.declarative import declarative_base 
Base = declarative_base() 

models1.py

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

models2.py:

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

helper.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() 

driver.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没有时间来初始化? (如果我正确地理解了答案),这里是主文件(的相关部分)的样子:

main。潘岳:

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 

driver.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))} 

我不知道为什么,从创建数据库基础中的元数据是不是gettng约束?

+0

是否在Category Category中的此行出现错字或粘贴错误? '__tablename__ ='business'' – brandaemon

+0

是的,我已经修复了 – Taaam

+0

[Python SqlAlchemy - AttributeError:mapper]的可能重复(https://stackoverflow.com/questions/45534903/python-sqlalchemy-attributeerror-mapper) –

回答

0

问题似乎已经消失,所以我会发布我的工作。这很简单。我重构了代码以明确提供类和经典映射器,而不是使用声明性基础,并且所有工作都再次正常......

0

我想这个错误是因为你在Python模块级上执行你的代码而发生的。 Python在导入模块时执行此代码。

  • 将您的代码移到一个函数。

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

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

  • 持续需要DBSession.configure(bind=engine)或相关的它会告诉模型的数据库连接它们是相关的。这个问题没有解决。

+0

嗯,我不这么认为?这个例子稍微简化了一些,实际上模型和驱动程序都在单独的子包中,驱动文件实际上是一个函数。包级主文件调用驱动程序文件。我将添加一个编辑来正确解释这一点。 – Taaam

+0

为答案增加了一些想法。 –

+0

我有'''setupDB() - > create_all'''来显示SQLAlchemy被加载并且知道模型,当我调用'updateDBFromFile''的时候。在实践中,该行被注释掉。 '''getDBSession(echo = True)'''''''''''''''''''''''''''''''' ''' – Taaam