I have a project where i want to isolate DB initialization (SQLAlchemy) from the other module so i've create a module
db_initializer.py
engine = create_engine('sqlite:///db') # TODO from config file
Session = sessionmaker(bind=engine)
Base = declarative_base(bind=engine)
def create_tables():
Base.metadata.create_all(engine)
First of all i need to put create_all in function because my model is in an other package
model/foo.py
from core.db_initializer import Base
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True)
name = Column(String)
def __init__(self, name: str = None):
self.name = name
def __repr__(self):
return "<User(id=%d, name=%s)>" % (int(self.id), str(self.name))
And my main call create_tables.
Is there any other to do that ? And now i need to create the engine with custom config (IP,User, ...) and only the main script know the config it's possible ?
Something like
main.py
import db_initializer as db
import model.foo
db.init(config) # which create the engine and create table
When i do something like that i got problem with the Base object which have not bind to the engine which is not created yet... Any solution ?
Aucun commentaire:
Enregistrer un commentaire