为什么会出现“ AttributeError:'NoneType'对象没有属性”?

时间:2020-07-30 20:12:53

标签: python sqlalchemy

此代码可以正常工作:

Base = declarative_base()

Session = sessionmaker()
Base = declarative_base()

engine = create_engine("mysql+mysqlconnector://root:root@localhost/")

Base.metadata.create_all(engine)

Session.configure(bind=engine)
session = Session()


class MatchesATP(Base):
    __tablename__ = "matches_atp"
    __table_args__ = {"schema": "belgarath",
                      "extend_existing": True}

    ID_M = Column(Integer, primary_key=True)
    ID_T_M = Column(Integer, ForeignKey("oncourt.tours_atp.ID_T"))


query = session.query(MatchesATP)
print([result for result in query])

我现在正在尝试构建访问层:

class DataAccessLayer():

    def __init__(self):
        conn_string = "mysql+mysqlconnector://root:root@localhost/"
        self.engine = create_engine(conn_string)
        Base.metadata.create_all(self.engine)
        Session = sessionmaker()
        self.session = Session()

我使用以下方法创建它:

dal = DataAccessLayer()

然后尝试运行查询:

query = dal.session.query(MatchesATP)
print([result for result in query])

但是我遇到以下错误:

Traceback (most recent call last):
  File "c:/Users/Philip/OneDrive/Betting/Capra/Tennis/polgara/db_interface_orm_so.py", line 34, in <module>
    print([result for result in query])
  File "C:\Users\Philip\.conda\envs\polgara\lib\site-packages\sqlalchemy\orm\query.py", line 3481, in __iter__
    return self._execute_and_instances(context)
  File "C:\Users\Philip\.conda\envs\polgara\lib\site-packages\sqlalchemy\orm\query.py", line 3503, in _execute_and_instances
    querycontext, self._connection_from_session, close_with_result=True
  File "C:\Users\Philip\.conda\envs\polgara\lib\site-packages\sqlalchemy\orm\query.py", line 3518, in _get_bind_args
    mapper=self._bind_mapper(), clause=querycontext.statement, **kw
  File "C:\Users\Philip\.conda\envs\polgara\lib\site-packages\sqlalchemy\orm\query.py", line 3496, in _connection_from_session
    conn = self.session.connection(**kw)
  File "C:\Users\Philip\.conda\envs\polgara\lib\site-packages\sqlalchemy\orm\session.py", line 1136, in connection
    bind = self.get_bind(mapper, clause=clause, **kw)
  File "C:\Users\Philip\.conda\envs\polgara\lib\site-packages\sqlalchemy\orm\session.py", line 1577, in get_bind
    % (", ".join(context))
sqlalchemy.exc.UnboundExecutionError: Could not locate a bind configured on mapper mapped class MatchesATP->matches_atp, SQL expression or this Session

这篇帖子here建议替换:

self.session = Session()

使用:

self.session = Session.configure(bind=self.engine)

但是,这样做会出现以下错误:

Traceback (most recent call last):
  File "c:/Users/Philip/OneDrive/Betting/Capra/Tennis/polgara/db_interface_orm_so.py", line 32, in <module>
    query = dal.session.query(MatchesATP)
AttributeError: 'NoneType' object has no attribute 'query'

关于我可以从这里去哪里的任何想法?

0 个答案:

没有答案