2

run.py

db = SQLAlchemy()
migrate = Migrate()

def create_app():
    app = Flask(__name__)
    db.app = app
    db.init_app(app)
    migrate.init_app(app, db)
    return app

if __name__ == '__main__':
    application = create_app()
    application.run()

manage.py

from flask_migrate import MigrateCommand, Manager

from run import create_app


manager = Manager(create_app())
manager.add_command('db', MigrateCommand)

When I run: python manage.py db init

Traceback (most recent call last):
  File "manage.py", line 6, in <module>
    manager = Manager(create_app())
TypeError: 'NoneType' object is not callable

When I run: flask db init

Usage: flask db init [OPTIONS]

Error: Could not locate Flask application. You did not provide the FLASK_APP environment variable.

For more information see http://flask.pocoo.org/docs/latest/quickstart/

I try to export FLASK_APP as run, run.py, run.create_app, run:create_app(), yet I still get the error shown above. What is causing this error?

SeeDerekEngineer
  • 770
  • 2
  • 6
  • 22
Gep Gecici
  • 77
  • 1
  • 8

2 Answers2

3

flask_migrate will attempt to use Manager from flask-script, but only if flask-script is installed.

Simply do, and it should work. You can also import directly from flask_script.

pip install flask_script

manage.py

from flask_migrate import MigrateCommand
from flask_script import Manager
from run import create_app

app = create_app()
manager = Manager(app)
manager.add_command('db', MigrateCommand)
Runar
  • 245
  • 3
  • 17
2

There are two ways to run the Flask-Migrate commands. The newer method uses the Flask CLI, the older uses Flask-Script. Since you don't seem to have Flask-Script installed, I'm going to assume that you intend to use the Flask CLI.

So you need to throw away manage.py since that only applies to Flask-Script. Then move your application variable to the global scope:

db = SQLAlchemy()
migrate = Migrate()

def create_app():
    app = Flask(__name__)
    db.app = app
    db.init_app(app)
    migrate.init_app(app, db)
    return app

application = create_app()

if __name__ == '__main__':
    application.run()

Then set your FLASK_APP variable:

$ export FLASK_APP=run.py

And now you should be able to run the application with flask run, and the database commands with flask db <command>.

Miguel Grinberg
  • 65,299
  • 14
  • 133
  • 152