简体   繁体   中英

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.

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

Set FLASK_APP as an environment variable:

export FLASK_APP=db_table.py

before running your flask command-line app.

See the Command Line Interface documentation :

For the flask script to work, an application needs to be discovered. This is achieved by exporting the FLASK_APP environment variable. It can be either set to an import path or to a filename of a Python module that contains a Flask application.

You can also set the variable per command by setting it on the same command line:

FLASK_APP=db_table.py flask db init

You can refer to this documentation to learn how to set environment variables in Flask.

Unix Bash (Linux, Mac, etc.):

$ export FLASK_APP=hello
$ flask run

Windows CMD:

> set FLASK_APP=hello
> flask run

Windows PowerShell:

> $env:FLASK_APP = "hello"
> flask run

Some problem will can happen if you use DispatcherMiddleware (werkzeug.wsgi). Change return object from app_dispatch to app without app_dispatch for migrate time.

This is a rare case, I hope someone helps...

In VS code editor, click on Run and Debug. Select Flask debugger and type your file name. This worked for me and hope it works for you too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM