Search code examples
pythonflaskflask-sqlalchemydatabase-migration

Flask app getting error of "could not locate flask application. .....FLASK_APP environment variable" for Flask Migrate


I have a file db_table.py that looks like:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_migrate import Migrate

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:password@localhost/mydb'

db = SQLAlchemy(app)
migrate = Migrate(app, db)
.....db tables....

When I try to run:

flask db init

I get:

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

I tried first manually setting FLASK_APP var, by doing set FLASK_APP=app.py then running flask db init again, but that didn't resolve the issue.


Solution

  • The flask command line argument needs to know what module to locate the current Flask app instance in.

    You can pass in the module name using the --app argument:

    flask —-app db_table
    

    See the Command Line Interface documentation:

    The flask command is installed by Flask, not your application; it must be told where to find your application in order to use it. The --app option is used to specify how to load the application.

    Alternatively, you can set the environment variable FLASK_APP; the flask command will use its value if there is no --app command-line switch:

    export FLASK_APP=db_table