Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask-SQLAlchemy - When are the tables/databases created and destroyed?

I am a little confused with the topic alluded to in the title.

So, when a Flask app is started, does the SQLAlchemy search theSQLALCHEMY_DATABASE_URI for the correct, in my case, MySQL database. Then, does it create the tables if they do not exist already?

What if the database that is programmed into theSQLALCHEMY_DATABASE_URI variable in the config.py file does not exist?

What if that database exists, and only a few of the tables exist (There are more tables coded into the SQLAlchemy code than exist in the actual MySQL database)? Does it erase those tables and then create new tables with the current specs?

And what if those tables do all exist? Do they get erased and re-created?

I am trying to understand how the entire process works so that I (1) Don't lose database information when changes are made to the schema, and (2) can write the necessary code to completely manage how and when the SQLAlchemy talks to the actual Database.

like image 987
Alex Chumbley Avatar asked Jan 20 '14 20:01

Alex Chumbley


1 Answers

Tables are not created automatically; you need to call the SQLAlchemy.create_all() method to explicitly to have it create tables for you:

db = SQLAlchemy(app)
db.create_all()

You can do this with command-line utility, for example. Or, if you deploy to a PaaS such as Google App Engine, a dedicated admin-only view.

The same applies for database table destruction; use the SQLAlchemy.drop_all() method.

See the Creating and Dropping tables chapter of the documentation, or take a look at the database chapter of the Mega Flask Tutorial.

You can also delegate this task to Flask-Migrate or similar schema versioning tools. These help you record and edit schema creation and migration steps; the database schema of real-life projects is never static and you would want to be able to move existing data between versions or the schema. Creating the initial schema is then just the first step.

like image 91
Martijn Pieters Avatar answered Nov 17 '22 03:11

Martijn Pieters