1

I have a flask-appbuilder (FAB) project and I would like to use flask-migrate to handle db migrations. However FAB creates the db on its own beforehand, so that flask-migrate cannot compute the migrations

I'm aware of this example and of this issue on FAB's repository, however I wasn't able to use them to solve the problem.

This is a minimal app to show the problem.

# app.py
from flask import Flask
from flask_appbuilder import AppBuilder, SQLA
from flask_migrate import Migrate
import os
from flask_appbuilder import Model
from sqlalchemy import Column, Integer


class Config():
    basedir = os.path.abspath(os.path.dirname(__file__))
    SQLALCHEMY_DATABASE_URI = \
        'sqlite:///' + os.path.join(basedir, 'app.db')
    SQLALCHEMY_TRACK_MODIFICATIONS = False


db = SQLA()
migrate = Migrate()
appbuilder = AppBuilder()


def create_app(config_class=Config):
    app = Flask(__name__)
    app.config.from_object(config_class)
    db.init_app(app)
    migrate.init_app(app, db)

    with app.app_context():
        appbuilder.init_app(app, db.session)
        appbuilder.post_init()

    return app


class MyTable(Model):
    __tablename__ = "my_table"

    id = Column(Integer, primary_key=True)
    mycol = Column(Integer)


if __name__ == "__main__":
    app = create_app()
    app.run()

It can be tested in a virtual environment with the following requirements.txt:

flask-appbuilder==3.1.0
SQLAlchemy==1.3.24
flask-migrate

By issuing

export FLASK_APP=app.py
flask db init
flask db migrate

the output reads INFO [alembic.env] No changes in schema detected, so no migration. However the db has been created.

Note: crossposting from my issue on FAB's repo

japs
  • 1,286
  • 13
  • 27
  • 1
    I don't use FAB so this is just a suggestion that may or may not work, but have you tried deleting the initial database tables that FAB creates? If you delete the tables and then run `flask db migrate` I think the migration will be generated, and from that point on you can use Flask-Migrate to manage your db. – Miguel Grinberg Jun 18 '21 at 09:36
  • @Miguel, unfortunately the tables are created automatically by FAB initialisation. The lead developer will add a new config to allow for the standard migration pattern: https://github.com/dpgaspar/Flask-AppBuilder/issues/1654#issuecomment-864117219 – japs Jun 22 '21 at 15:50

1 Answers1

0

This solved the problem for me.

$ flask db stamp head # Set current revision in the database to be head
$ flask db migrate
$ flask db upgrade
Lenin
  • 303
  • 2
  • 3