I am trying to use engine_from_config() in the constructor of a class. The tutorials and material on the internet are so confusing. I am new to this and have been struggling with what seems to be a simple task. Any help on implementing .engine_from_config() in the constructor is truly appreciated!
This makes sense to me:
class BaseAPI(object):
_userclass = None
_userassessment = None
def __init__(self, config, prefix='sqlalchemy.', **kwargs):
assert self_userclass is not None
config = {'sqlalchemy.url':
'sqlite:///./somedb.db', 'sqlalchemy.echo':'True'}
self.engine = sqlalchemy.engine_from_config(config)
dbSession = scoped_session(sessionmaker(autoflush = True,
autocommit = False,
bind = engine))
Base.metadata.create_all(bind=engine)
print('--start DB Session--')
return dbSession
But in the tutorials I read that the way to implement sqlalchemy.engine_from_config is by this:
options = dict((key[len(prefix):], configuration[key])
for key in configuration
if key.startswith(prefix))
options['_coerce_config'] = True
options.update(kwargs)
url = options.pop('db')
return create_engine(url, **options)
I think I may be over thinking this or maybe the later is for an actual class called sqlalchemy.engine_from_config....Why doesn't my code work for me?
New Working Changes:
class BaseAPI(object):
def __init__(self):
config = {'sqlalchemy.url':'sqlite:///./somedb.db', 'sqlalchemy.echo':'True'}
self.engine = engine_from_config(config, prefix='sqlalchemy.')
Session = sessionmaker(autoflush=True,autocommit=False,bind=engine)
self.session = Session()
Base.metadata.create_all(bind=engine)
NEW QUESTION: Do I have to return my session? Also, shouldn't I need to have a 'create_engine' call in my init constructor? I have it in another file and I believe that is why this is working.
I would do the following. Use a shorter prefix like 'db.'. Don't forget the dot at the end. prefix='sqlalchemy.' is the default value so you don't have to write it in your code. This is also valid for the omitted parameters for sessionmaker.
config = {'db.url':'sqlite:///./somedb.db', 'db.echo':'True'}
self.engine = engine_from_config(config, prefix='db.')
Session = sessionmaker(bind=engine)
You should use the
Base.metadata.create_all(bind=engine)
if you want sqlalchemy create the tables for you. If the database exists you should use the engine_from_config.
I hope it helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With