user1443362
user1443362

Reputation: 645

Using a SQLAlchemy session from a separate python file

I have created a sqlite DB using SQLAlchemy and am trying to query one of the tables from a class in a different file from the one that I instantiated the db in. However, whenever I make a query it doesn't do anything. So I'm wondering how do I properly make a query using SQLAlchemy in the function of a class in a separate file. A very generalized idea of what I'm doing is below.

main.py:

**imports here**
engine = create_engine('sqlite:///info.db')
Session = sessionmaker(bind=engine)
Base = declarative_base()

class User(Base):
    __tablename__ = 'users'

    user_id = Column(String, primary_key=True)
    hash_of_password = Column(String)
    display_name = Column(String)
    full_name = Column(String)
    confirmed_account = Column(Boolean, default=True)

Base.metadata.create_all(engine)

numRows = CountRows().returnNumRows()

CountRows.py:

from main import Session

class CountRows:
    def returnNumRows(self):
        dbSession = Session()
        numRows = dbSession.query(User).count()
        print(numRows) #This is just for testing purposes to see if I actually got anything
        return numRows

Upvotes: 0

Views: 1138

Answers (1)

chishaku
chishaku

Reputation: 4643

In CountRows.py, include:

 from main import Session, User

Upvotes: 1

Related Questions