Cross-file SQLAlchemy class, does not create tables
I’m trying to create an application using SQLAlchemy. As long as I only have a file of one class, it works fine. Now I want to have multiple classes/tables in different files. I stumbled upon this issue and tried to follow the advice there: I now have three files
Basic .py
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
Blind .py
from sqlalchemy import Column, String
from .base import Base
class Blind(Base):
__tablename__ = 'blinds'
blind = Column(String)
data_processor_uuid = Column(String, primary_key=True)
data_source_uuid = Column(String)
timestamp = Column(String, primary_key=True)
and data.py
from sqlalchemy import Column, Integer, String, Float
from .base import Base
class Datum(Base):
__tablename__ = 'data'
data_source_uuid = Column(Integer, primary_key=True)
sensor_type = Column(String)
timestamp = Column(String, primary_key=True)
value = Column(Float)
I now want to initialize the database with db_setup.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from .base import Base
engine = create_engine('sqlite:///test.db', echo=True)
Base.metadata.bind = engine
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
session = Session()
def get_db_session():
return session
This works, however, it does not create tables in the database as expected. When I try to insert something into a table, I get a “table does not exist” error message. Can someone tell me what I’m doing wrong here?
Solution
The problem is that I didn’t import the class definitions for Blinds and Datum anywhere, so they weren’t evaluated! Before I split them into different files, I had imported them into Base. Thanks @IljaEverilä for your answer!