Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy classes across files, tables are not created

I am trying to create an application using SQLAlchemy. It worked fine as long as I only had one file with one Class. Now I want to have multiple classes/tables in different files. I stumbled upon this question, and tried to do it like it was suggested there: I now have three files

base.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 in db_setup.py using

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 the tables in the database as expected. When I try to insert something into the table, I get an error saying "table does not exist". Can someone tell me what I am doing wrong here?

like image 555
Gasp0de Avatar asked Oct 18 '25 16:10

Gasp0de


1 Answers

The problem was that I wasn't importing the class definitions for Blinds and Datum anywhere, so they weren't evaluated! Before I split them up into different files, I had imported them to get to Base. Thanks to @IljaEverilä for this answer!

like image 62
Gasp0de Avatar answered Oct 21 '25 06:10

Gasp0de



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!