通过sqlalchemy构造表时遇到麻烦

时间:2020-09-11 20:02:48

标签: python database postgresql sqlalchemy psycopg2

我正在尝试根据我使用psycopg2创建的连接到PostGres的模型在SqlAlchemy中创建表。由于某些原因,当我调用Base.metadata.create_all(engine)时,它引发错误AttributeError:'tuple'对象没有属性'_run_visitor'。我曾尝试寻找此错误,但实际上并不清楚其含义。我不知道是否需要使用其他版本的Python或其他版本。我正在使用Python 3.8和SqlAlchemy版本1.3.19。这是与我要执行的操作相关的代码。如果这很烦人,可以在https://github.com/u1209855/baseball处查看我的gitHub存储库。非常感谢!回购中将需要比这里更多的信息,我想这是您回答问题所需的全部信息。对此的编辑是我做了echo = True,看来它确实连接到了psql数据库,所以我不确定为什么它不能创建那些表...另一种编辑,尝试下载过往版本的sqlalchemy但没有运气。

from sqlalchemy import Column, INTEGER, NVARCHAR, TIMESTAMP, ForeignKey, DECIMAL, UniqueConstraint, JSON, \
FLOAT, VARCHAR, DATE
from database import Base


class Master(Base):
   __tablename__ = "master"
   __table_args__ = {"schema": "public"}
   playerID = Column(VARCHAR(10), primary_key=True)
   birthYear = Column(VARCHAR(4))
   birthDay = Column(INTEGER)
   birthCountry = Column(VARCHAR(15))
   birthState = Column(VARCHAR(30))
   deathYear = Column(VARCHAR(4))
   deathMonth = Column(INTEGER)
   deathDay = Column(INTEGER)
   deathCountry = Column(VARCHAR(15))
   deathState = Column(VARCHAR(30))
   deathCity = Column(VARCHAR(30))
   nameFirst = Column(VARCHAR(20))
   nameLast = Column(VARCHAR(20))
   nameGiven = Column(VARCHAR(60))
   weight = Column(INTEGER)
   height = Column(INTEGER)
   bats = Column(VARCHAR(1))
   debut = Column(DATE)
   finalGame = Column(DATE)
   retroID = Column(VARCHAR(10))
   bbrefID = Column(VARCHAR(10))


def create_models(engine):
   # print("dropping tables")
   # Base.metadata.drop_all(engine)
   print("creating tables")
   Base.metadata.create_all(engine)

这是我的数据库。py

    import sqlalchemy
    import os
    import models as m
    from sqlalchemy.ext.declarative import declarative_base
    from sqlalchemy.orm import sessionmaker
    Base = declarative_base()


  def sqlalchemy_connect():
     conn_str = 'postgresql+psycopg2://{user}:{password}@localhost:5432/{database}'.\
     format(user="postgres",
           password="some_password",
           database='baseball')
     engine = sqlalchemy.create_engine(conn_str
                                  ,use_batch_mode=True
                                  ,server_side_cursors=True)
     Session = sqlalchemy.orm.sessionmaker(autoflush=False)
     Session.configure(bind=engine)
     session = Session()
     return engine, session


def sqlalchemy_session():
   engine = sqlalchemy_connect()
   session = sqlalchemy.orm.scoped_session(sqlalchemy.orm.sessionmaker())
   session.configure(bind=engine, autoflush=False, expire_on_commit=False)
   return engine, session


def main():
   engine = sqlalchemy_connect()
   m.create_models(engine)

这是我跑步的主要内容。

    import models as m
    import database as db

    if __name__ == '__main__':
       engine, session = db.sqlalchemy_session()
       m.create_models(engine)

1 个答案:

答案 0 :(得分:0)

就像我的函数sqlalchemy_connect()只是需要返回引擎,而不是会话,它似乎可以解决问题。