Reputation: 9345
I have a basic script that creates a bunch of objects of class Player and then saves them into my DB (using SQLAlchemy). My main method used to look like this:
def main():
#create engine (for use by base and session)
engine = databaseFunctions.createEngine()
#create session
session = databaseFunctions.createSession(engine)
databaseFunctions.updateEntireDB(allPlayers, session)
And now I've changed it to this:
def main():
#create engine (for use by base and session)
engine = databaseFunctions.createEngine()
#create session
session = databaseFunctions.createSession(engine)
#list all players in DB
databaseFunctions.allPlayers(session)
After running main() with the 1st definition, I closed my shell, re-opened and ran main() with the new definition. All of my DB objects seem to print correctly (so it looks like they're persisted between session creations).
Is it normal to run a function once to "initialize the DB" and then only update it thereafter (given that it'll just need updates)? Seems like bad practice to change my main after running it with initialization code...
Upvotes: 0
Views: 103
Reputation: 18908
To your first question, yes it is perfectly normal, however you definitely want to provide that as an initialization/migration step as part of your application. Assuming you want to put this as part of your databaseFunction
module, you might want something like this:
In your databaseFunctions.py
def checkDB(engine):
session = createSession(engine)
# use the session here to check the database
# return True if the tables for your app are properly created/updated
# ... your database functions.
In your entry point module:
def main():
engine = databaseFunctions.createEngine()
session = databaseFunctions.createSession(engine)
# could be rolled into databaseFunctions
if not databaseFunctions.checkDB():
databaseFunctions.updateEntireDB(allPlayers, session)
# list all players in DB
databaseFunctions.allPlayers(session)
You may want to consider reviewing the documentation on the Session API for sqlalchemy
.
Upvotes: 1