I have a database db. I want to judge if flask_migrate has created tables in db. If not, upgrade db.
There are commands, but no examples about calling migrate, upgrade in python script.
The test files in flask_migrate also run commands, such as:
(o, e, s) = run_cmd('python app.py db migrate')
The tests are based on the most common usage, which is people running the commands manually from the shell.
But all commands have an API version, which is documented here: https://flask-migrate.readthedocs.io/en/latest/#api-reference. For an example, see https://github.com/miguelgrinberg/flasky/blob/master/manage.py#L67-L71.
You can also use the Alembic API if you need low level access.
If anyone else lands here searching for a way to run migrations on start of your app (e.g. useful for containerized flask apps) here is how I do it:
...
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate
...
db = SQLAlchemy(app)
migrate = Migrate(app, db)
# apply any/all pending migrations.
with app.app_context():
from flask_migrate import upgrade as _upgrade
_upgrade()
Take caution to ensure that you handle migrations and corresponding app code in a manner that works with migrations being applied on start of the app (e.g. if you have multiple instances of your app running in a containerized/load balanced manner make sure one updating of one of the containers does not break other containers).
If you're curious how to run flask db init/migrate/upgrade from a click command...
import click
from flask.cli import with_appcontext
from flask_migrate import init, migrate, upgrade
...
@click.command()
@with_appcontext
def setup_db():
init_db = init()
migrate_db = migrate()
upgrade_db = upgrade()
Then you'd call this at the CLI with:
flask setup_db
Most helpful comment
If anyone else lands here searching for a way to run migrations on start of your app (e.g. useful for containerized flask apps) here is how I do it:
Take caution to ensure that you handle migrations and corresponding app code in a manner that works with migrations being applied on start of the app (e.g. if you have multiple instances of your app running in a containerized/load balanced manner make sure one updating of one of the containers does not break other containers).